Installs all partitons of the table and create view with union of all partitons.

        Args:
            connection: connection to database who stores mpr data.
            table (orm.Table):
15177
def install_table(self, connection, table, logger = None):
        
        # first install all partitions of the table

        queries = []
        query_tmpl = 'SELECT * FROM {}'
        for partition in table.partitions:
            partition.localize()
            installed_name = self.install(connection, partition)
            queries.append(query_tmpl.format(installed_name))

        # now create view with union of all partitions.
        query = 'CREATE VIEW {} AS {} '.format( table.vid, '\nUNION ALL\n'.join(queries))
        logger.debug('Creating view for table.\n    table: {}\n    query: {}'.format(table.vid, query))
        self._execute(connection, query, fetch=False)
507958
private void addOrUpdateTable(File file) {
        try {
            String insertStmnt = FileUtils.readFileToString(file);
            DataSource ds = processSql(insertStmnt);
            DataSource existingDs = db().getDataSource(ds.getName());
            if (existingDs == null) {//We never saw this table before.
                db().addDataSource(ds);
                return;
            }
            // If startTime/endTime/templatePath changed then we should update the table.
            if (existingDs.getStartTime() != ds.getStartTime() || 
                    existingDs.getEndTime() != ds.getEndTime() ||
                    !existingDs.getTemplatePath().equals(ds.getTemplatePath())) {
                // We have to reuse the existing entity bean(else update will fail).
                existingDs.updateFrom(ds);
                db().updateDataSource(existingDs);
            }                 
        } catch (IOException ex) {
            log.error("Exception while loading druid sql file {} : {}", file, ex);
        }
    }
667545
public Connection createConnectionProxy(Connection connection) {
		assert connection != null;
		// même si le counter sql n'est pas affiché on crée un proxy de la connexion
		// pour avoir les graphiques USED_CONNECTION_COUNT et ACTIVE_CONNECTION_COUNT (cf issue 160)
		if (isMonitoringDisabled()) {
			return connection;
		}
		final ConnectionInvocationHandler invocationHandler = new ConnectionInvocationHandler(
				connection);
		final Connection result = createProxy(connection, invocationHandler);
		if (result != connection) {
			invocationHandler.init();
		}
		return result;
	}
903848
def syncdb():
    
    from flask_philo.db.postgresql.schema import Base
    from flask_philo.db.postgresql.orm import BaseModel  # noqa
    from flask_philo.db.postgresql.connection import get_pool

    for conn_name, conn in get_pool().connections.items():
        Base.metadata.create_all(conn.engine)
132450
def connect_db(Repo, database=":memory:"):
        
        Repo.db = sqlite3.connect(database,
                                  detect_types=sqlite3.PARSE_DECLTYPES)
        return Repo.db
1081390
def mptt_before_insert(mapper, connection, instance):
    
    table = _get_tree_table(mapper)
    db_pk = instance.get_pk_column()
    table_pk = getattr(table.c, db_pk.name)

    if instance.parent_id is None:
        instance.left = 1
        instance.right = 2
        instance.level = instance.get_default_level()
        tree_id = connection.scalar(
            select(
                [
                    func.max(table.c.tree_id) + 1
                ]
            )
        ) or 1
        instance.tree_id = tree_id
    else:
        (parent_pos_left,
         parent_pos_right,
         parent_tree_id,
         parent_level) = connection.execute(
            select(
                [
                    table.c.lft,
                    table.c.rgt,
                    table.c.tree_id,
                    table.c.level
                ]
            ).where(
                table_pk == instance.parent_id
            )
        ).fetchone()

        # Update key of right side
        connection.execute(
            table.update(
                and_(table.c.rgt >= parent_pos_right,
                     table.c.tree_id == parent_tree_id)
            ).values(
                lft=case(
                    [
                        (
                            table.c.lft > parent_pos_right,
                            table.c.lft + 2
                        )
                    ],
                    else_=table.c.lft
                ),
                rgt=case(
                    [
                        (
                            table.c.rgt >= parent_pos_right,
                            table.c.rgt + 2
                        )
                    ],
                    else_=table.c.rgt
                )
            )
        )

        instance.level = parent_level + 1
        instance.tree_id = parent_tree_id
        instance.left = parent_pos_right
        instance.right = parent_pos_right + 1
485493
public void connectClient(Connection connection) {
    threadContext.checkThread();

    // Note we do not use method references here because the "state" variable changes over time.
    // We have to use lambdas to ensure the request handler points to the current state.
    connection.handler(RegisterRequest.class, (Function<RegisterRequest, CompletableFuture<RegisterResponse>>) request -> state.register(request));
    connection.handler(ConnectRequest.class, (Function<ConnectRequest, CompletableFuture<ConnectResponse>>) request -> state.connect(request, connection));
    connection.handler(KeepAliveRequest.class, (Function<KeepAliveRequest, CompletableFuture<KeepAliveResponse>>) request -> state.keepAlive(request));
    connection.handler(UnregisterRequest.class, (Function<UnregisterRequest, CompletableFuture<UnregisterResponse>>) request -> state.unregister(request));
    connection.handler(ResetRequest.class, (Consumer<ResetRequest>) request -> state.reset(request));
    connection.handler(CommandRequest.class, (Function<CommandRequest, CompletableFuture<CommandResponse>>) request -> state.command(request));
    connection.handler(QueryRequest.class, (Function<QueryRequest, CompletableFuture<QueryResponse>>) request -> state.query(request));

    connection.onClose(stateMachine.executor().context().sessions()::unregisterConnection);
  }
58991
public static function manyToMany($modelClass, $connection, $options = []) {
        $options['type'] = self::MANY_TO_MANY;
        $options['modelClass'] = $modelClass;
        $connection = explode('(', $connection);
        $table = $connection[0];
        list($c1, $c2) = explode(',', $connection[1]);
        $r = new self($options);
        $c1 = trim($c1);
        $c2 = trim($c2);
        $r->join(trim($table), [["t.__PK__", "j.$c1", "="]])
            ->compare(["j.$c2" => "r." . $modelClass::getDb()->getTablePk($modelClass::getTableName())]);
        return $r;
    }
37154
public void createTables(Connection connection, TableCreationMode mode, boolean createIndexes) {
        ArrayList<Type<?>> sorted = sortTypes();
        try (Statement statement = connection.createStatement()) {
            if (mode == TableCreationMode.DROP_CREATE) {
                ArrayList<Type<?>> reversed = sortTypes();
                Collections.reverse(reversed);
                executeDropStatements(statement, reversed);
            }
            for (Type<?> type : sorted) {
                String sql = tableCreateStatement(type, mode);
                statementListeners.beforeExecuteUpdate(statement, sql, null);
                statement.execute(sql);
                statementListeners.afterExecuteUpdate(statement, 0);
            }
            if (createIndexes) {
                for (Type<?> type : sorted) {
                    createIndexes(connection, mode, type);
                }
            }
        } catch (SQLException e) {
            throw new TableModificationException(e);
        }
    }
1099673
private void applyPerPartitionTxnId(SiteProcedureConnection connection) {
        //If there was no ID nothing to do
        long partitionTxnIds[] = fetchPerPartitionTxnId();
        if (partitionTxnIds == null) return;
        connection.setPerPartitionTxnIds(partitionTxnIds, true);
    }
822936
private function createBuilderFromConnection(Connection $connection, string $modelClass): ModelQueryBuilder
    {
        return $this->getFactory()->createModelQueryBuilder($connection, $modelClass, $this->getModelSchemas());
    }
734822
public static void createSchema(Connection connection, String dialect, boolean createSchemaMigrations) {
    if (createSchemaMigrations) {
      executeScript(connection, "org/sonar/db/version/schema_migrations-" + dialect + ".ddl");
    }
    executeScript(connection, "org/sonar/db/version/schema-" + dialect + ".ddl");
    executeScript(connection, "org/sonar/db/version/rows-" + dialect + ".sql");
  }
65641
private function createClientsView(Connection $connection, DatabaseSchemaInterface $schema)
    {
        $view             = $schema->getClientsView();
        $scopes           = $schema->getClientsViewScopesColumn();
        $redirectUris     = $schema->getClientsViewRedirectUrisColumn();
        $clientsScopes    = $schema->getClientsScopesTable();
        $clientsUris      = $schema->getRedirectUrisTable();
        $clients          = $schema->getClientsTable();
        $clientsClientId  = $schema->getClientsIdentityColumn();
        $clScopesClientId = $schema->getClientsScopesClientIdentityColumn();
        $clUrisClientId   = $schema->getRedirectUrisClientIdentityColumn();
        $urisValue        = $schema->getRedirectUrisValueColumn();
        $scopesScopeId    = $schema->getScopesIdentityColumn();
        $sql              = <<< EOT
CREATE VIEW {$view} AS
    SELECT
      c.*,
      array_remove(array_agg(s.{$scopesScopeId}), NULL) AS {$scopes},
      array_remove(array_agg(u.{$urisValue}), NULL)     AS {$redirectUris}
    FROM {$clients} AS c
      LEFT JOIN {$clientsScopes} AS s ON c.{$clientsClientId} = s.{$clScopesClientId}
      LEFT JOIN {$clientsUris}   AS u ON c.{$clientsClientId} = u.{$clUrisClientId}
    GROUP BY c.{$clientsClientId};
EOT;
        $connection->exec($sql);
    }
377456
def build(self, connection, grammar):
        
        for statement in self.to_sql(connection, grammar):
            connection.statement(statement)
232195
CompletableFuture<Void> connect(LocalConnection connection) {
    LocalConnection localConnection = new LocalConnection(listener.context, connections);
    connections.add(localConnection);
    connection.connect(localConnection);
    localConnection.connect(connection);
    return CompletableFuture.runAsync(() -> listener.listener.accept(localConnection), listener.context.executor());
  }
1143076
public void createIndexes(Connection connection, TableCreationMode mode) {
        ArrayList<Type<?>> sorted = sortTypes();
        for (Type<?> type : sorted) {
            createIndexes(connection, mode, type);
        }
    }
611860
def run(connection):
    

    parser = argparse.ArgumentParser(description="""
    Process database dumps.

    Either download of upload a dump file to the objectstore.

    downloads the latest dump and uploads with envronment and date
    into given container destination
    """)

    parser.add_argument(
        'location',
        nargs=1,
        default=f'{DUMPFOLDER}/database.{ENV}.dump',
        help="Dump file location")

    parser.add_argument(
        'objectstore',
        nargs=1,
        default=f'{DUMPFOLDER}/database.{ENV}.dump',
        help="Dump file objectstore location")

    parser.add_argument(
        '--download-db',
        action='store_true',
        dest='download',
        default=False,
        help='Download db')

    parser.add_argument(
        '--upload-db',
        action='store_true',
        dest='upload',
        default=False,
        help='Upload db')

    parser.add_argument(
        '--container',
        action='store_true',
        dest='container',
        default=False,
        help='Upload db')

    parser.add_argument(
        '--days',
        type=int,
        nargs=1,
        dest='days',
        default=0,
        help='Days to keep database dumps')

    args = parser.parse_args()

    if args.days:
        LOG.debug('Cleanup old dumps')
        remove_old_dumps(
            connection, args.objectstore[0], args.days[0])
    elif args.download:
        download_database(
            connection, args.objectstore[0], args.location[0])
    elif args.upload:
        upload_database(
            connection, args.objectstore[0], args.location[0])
    else:
        parser.print_help()