コード例 #1
0
ファイル: test_database.py プロジェクト: RyanLainchbury/zoom
 def setUp(self):
     self.db = database('mysql',
                        host='database',
                        user='******',
                        passwd='password',
                        db='zoomtest')
     self.create_cmd = """
         create table dzdb_test_table
         (
             ID CHAR(10),
             AMOUNT NUMERIC(10,2),
             salary decimal(10,2),
             NOTES TEXT
         )
     """
     self.create_indexed_cmd = """
         create table dz_test_contacts (
             contactid integer PRIMARY KEY AUTO_INCREMENT,
             userid char(20),
             password char(16),
             email char(60)
         )
     """
     self.db('drop table if exists dzdb_test_table')
     self.db.debug = True
コード例 #2
0
ファイル: test_database.py プロジェクト: robinsax/zoom
 def setUp(self):
     self.db = database('sqlite3', ':memory:')
     self.create_cmd = """
         create table dzdb_test_table
         (
             ID CHAR(10),
             AMOUNT NUMERIC(10,2),
             salary decimal(10,2),
             NOTES TEXT
         )
     """
     self.create_indexed_cmd = """
         create table dz_test_contacts (
             contactid integer PRIMARY KEY AUTOINCREMENT,
             userid char(20),
             password char(16),
             email char(60)
         )
     """
     self.db("""
         create table test_table
         (
             id char(10),
             amount numeric(10,2),
             salary decimal(10,0),
             notes text
         )
     """)
     self.db.execute_many('insert into test_table values (%s, %s, %s, %s)',
                          [
                              [1, 10.20, '50.00', 'notes 1'],
                              [2, 30.20, '75.00', 'notes 2'],
                              [3, 40.10, '20.00', 'notes 3'],
                          ])
     self.db.debug = True
コード例 #3
0
    def setUp(self):
        get = os.environ.get

        self.db = database(
            'mysql',
            host=get('ZOOM_TEST_DATABASE_HOST', 'localhost'),
            user=get('ZOOM_TEST_DATABASE_USER', 'testuser'),
            passwd=get('ZOOM_TEST_DATABASE_PASSWORD', 'password'),
            db='zoomtest'
        )
        self.create_cmd  = """
            create table dzdb_test_table
            (
                ID CHAR(10),
                AMOUNT NUMERIC(10,2),
                salary decimal(10,2),
                NOTES TEXT
            )
        """
        self.create_indexed_cmd = """
            create table dz_test_contacts (
                contactid integer PRIMARY KEY AUTO_INCREMENT,
                userid char(20),
                password char(16),
                email char(60)
            )
        """
        self.db('drop table if exists dzdb_test_table')
        self.db.debug = True
コード例 #4
0
ファイル: test_database.py プロジェクト: robinsax/zoom
    def setUp(self):
        get = os.environ.get

        self.db = database('mysql',
                           host=get('ZOOM_TEST_DATABASE_HOST', 'localhost'),
                           user=get('ZOOM_TEST_DATABASE_USER', 'testuser'),
                           passwd=get('ZOOM_TEST_DATABASE_PASSWORD',
                                      'password'),
                           db='zoomtest')
        self.create_cmd = """
            create table dzdb_test_table
            (
                ID CHAR(10),
                AMOUNT NUMERIC(10,1),
                salary decimal(10,2),
                NOTES TEXT
            )
        """
        self.create_indexed_cmd = """
            create table dz_test_contacts (
                contactid integer PRIMARY KEY AUTO_INCREMENT,
                userid char(20),
                password char(16),
                email char(60)
            )
        """
        self.db('drop table if exists dzdb_test_table')
        self.db('drop table if exists test_table')
        self.db("""
            create table test_table
            (
                id char(10),
                amount numeric(10,1),
                salary decimal(10,0),
                notes text
            )
        """)
        self.db.execute_many('insert into test_table values (%s, %s, %s, %s)',
                             [
                                 [1, 10.20, '50.00', 'notes 1'],
                                 [2, 30.20, '75.00', 'notes 2'],
                                 [3, 40.10, '20.00', 'notes 3'],
                             ])
        self.db.debug = True
コード例 #5
0
ファイル: test_database.py プロジェクト: RyanLainchbury/zoom
 def setUp(self):
     self.db = database('sqlite3', ':memory:')
     self.create_cmd = """
         create table dzdb_test_table
         (
             ID CHAR(10),
             AMOUNT NUMERIC(10,2),
             salary decimal(10,2),
             NOTES TEXT
         )
     """
     self.create_indexed_cmd = """
         create table dz_test_contacts (
             contactid integer PRIMARY KEY AUTOINCREMENT,
             userid char(20),
             password char(16),
             email char(60)
         )
     """
     self.db.debug = True
コード例 #6
0
def do_database_creation(argument_source, collected=dict()):
    """Perform a database creation, including wizarding for required values not
    present in the provided argument source parsed by docopt. The caller can
    supply a set of already-collected applicable options to prevent entry
    duplication."""

    # Decide which arguments need to be collected based on what has already
    # been collected; then collect those and merge the two sets.
    to_collect = list(
        filter(lambda option: option[1] not in collected, DB_CREATION_OPTIONS))
    collected = {**collected, **collect_options(argument_source, to_collect)}

    # Parse and pop some options from the collected set.
    engine = collected['engine']
    db_name = re.sub(r'[^\w_]', '_', collected.pop('database'))
    force = collected.pop('force')
    # Validate and cast port number.
    if 'port' in collected:
        try:
            collected['port'] = int(collected['port'])
        except ValueError:
            finish(True, 'Error: invalid port number')

    # Acquire a connection and maybe create a database based on the engine.
    db = None
    if engine == 'mysql':
        try:
            db = database(**collected)
        except (OperationalError, InternalError) as err:
            if not collected['password']:
                # The user may be attempting to initialize as a root user with
                # no configured password. pymysql doesn't let us authenticate
                # in that case, so we provide a (hopefully) helpful error.
                finish(
                    True,
                    'Error: invalid database credentials (authentication with'
                    ' empty passwords isn\'t supported)')
            else:
                # Otherwise we provide a more generic error.
                finish(True,
                       'Error: invalid database credentials (%s)' % (str(err)))
        # If this database already exists drop it if this operation is forced
        # or die.
        if db_name in db.get_databases():
            if force:
                db('drop database %s' % db_name)
            else:
                finish(True, 'Error: database "%s" already exists' % db_name)
        # Create the database and switch to it.
        db('create database %s;' % db_name)
        db('use %s;' % db_name)
    elif engine == 'sqlite3':
        # TODO(sqlite3 support): We should not collect these options instead.
        # XXX(sqlite3 support): How do we handle --force for sqlite?
        if collected:
            finish(True, 'Error: sqllite3 doesn\'t support extra options')
        db = database('sqlite3', db_name)
    else:
        finish(True, 'Error: engine "%s" isn\'t supported yet' % engine)

    # Create the stock Zoom tables and return the active handle with some
    # collected metadata.
    db.create_site_tables()
    print('Created Zoom database "%s"' % db_name)
    return db, db_name, collected.pop('host')
コード例 #7
0
ファイル: test_database.py プロジェクト: robinsax/zoom
 def setUp(self):
     self.db = database('sqlite3', ':memory:')
コード例 #8
0
ファイル: describe.py プロジェクト: zodman/ZoomFoundry
def describe():
    # Parse the provided arguments, resolving which command is running and
    # wizarding any missing options.
    arguments = docopt(doc=describe.__doc__)
    which = which_argument(arguments, ('databases', 'database', 'background'))
    
    def output(result):
        """Output a database query result with formatting."""
        print(str(result).join(('\n=======\n',)*2))

    # Connect to the database.
    collected = db = None
    if which.startswith('database'):
        collected = collect_options(arguments, COMMAND_OPTIONS)
        db = database(**collected)

    if which == 'databases':
        # Describe the set of databases.
        output(db('show databases;'))
    elif which == 'database':
        # Resolve whether an individual table is being referenced.
        db_name = arguments['<db_or_table>']
        table_name = None
        if '.' in db_name:
            db_name, table_name, *rest = db_name.split('.')
            if len(rest):
                finish(True, 'Error: invalid table reference "%s"'%(
                    arguments['<db_or_table>']
                ))
        
        # Switch to the requested database with safety.
        try:
            db('use %s;'%db_name)
        except:
            finish(True, 'Error: invalid database "%s"'%db_name)

        if table_name:
            # Describe an individual table.
            try:
                output(db('describe %s;'%table_name))
            except:
                finish(True, 'Error: invalid table "%s"'%table_name)
        else:
            # Describe the table set for this database.
            output(db('show tables;'))
    elif which == 'background':
        # Resolve the path to the site or instance target.
        target_path = os.path.join(resolve_path_with_context(
            arguments.get('<path>') or '.',
            site=True, instance=True
        ))

        count = None

        def list_site_jobs(site):
            """List background job functions for a site."""
            site.activate()
            for job in site.background_jobs:
                changed = job.has_changed_since_record()
                print('%s%s: %s'%(
                    job.qualified_name, ' [changed]' if changed else str(),
                    job.uow.__doc__
                ))

        def list_site_events(site):
            """List background job events for a site."""
            site.activate()
            for job in site.background_jobs:
                runtimes = job.get_runtimes()
                print('Job: %s'%job.qualified_name)
                for i, runtime in enumerate(runtimes):
                    if i >= count:
                        break
                    print('\t%s'%runtime.describe())

        # Decide which description function to use.
        is_events_query = arguments.get('--events')
        if is_events_query:
            count = arguments.get('--count') or 10
            try:
                count = int(count)
            except ValueError:
                finish(True, 'Error: invalid count')
        
        action_fn = list_site_events if is_events_query else list_site_jobs
        
        if is_site_dir(target_path):
            # Run on the given site only.
            action_fn(Site(target_path))
        elif is_instance_dir(target_path):
            # Run on each site in the instance.
            instance = Instance(target_path)
            for site in instance.get_sites(skip_fails=True).values():
                action_fn(site)
        else:
            finish(True, 'Error: "%s" is not a Zoom site or instance'%(
                target_path
            ))
    else:
        raise NotImplementedError()

    print('Described')