Search in sources :

Example 31 with Query

use of org.jooq.Query in project jOOQ by jOOQ.

the class DDLDatabase method load.

private void load(DSLContext ctx, Source source) {
    Reader r = null;
    try {
        Scanner s = new Scanner(r = source.reader()).useDelimiter("\\A");
        Queries queries = ctx.parser().parse(s.hasNext() ? s.next() : "");
        for (Query query : queries) {
            repeat: for (; ; ) {
                try {
                    if (logExecutedQueries)
                        log.info(query);
                    if (logExecutedQueries && logExecutionResults)
                        if (query instanceof ResultQuery)
                            log.info("\n" + ((ResultQuery<?>) query).fetch());
                        else
                            log.info("Update count: " + query.execute());
                    else
                        // [#10008] Execute all queries. Could have FOR UPDATE or other side effects
                        query.execute();
                    break repeat;
                } catch (DataAccessException e) {
                    // [#7039] Auto create missing schemas. We're using the
                    if (Integer.toString(ErrorCode.SCHEMA_NOT_FOUND_1).equals(e.sqlState())) {
                        SQLException cause = e.getCause(SQLException.class);
                        if (cause != null) {
                            Matcher m = P_NAME.matcher(cause.getMessage());
                            if (m.find()) {
                                Query createSchema = ctx.createSchemaIfNotExists(name(m.group(1)));
                                createSchema.execute();
                                log.info(createSchema);
                                continue repeat;
                            }
                        }
                    }
                    throw e;
                }
            }
        }
    } catch (DataAccessException e) {
        // [#9138] Make users aware of the new parse ignore comment syntax
        log.error("DDLDatabase Error", "Your SQL string could not be parsed or interpreted. This may have a variety of reasons, including:\n" + "- The jOOQ parser doesn't understand your SQL\n" + "- The jOOQ DDL simulation logic (translating to H2) cannot simulate your SQL\n" + "\n" + "If you think this is a bug or a feature worth requesting, please report it here: https://github.com/jOOQ/jOOQ/issues/new/choose\n" + "\n" + "As a workaround, you can use the Settings.parseIgnoreComments syntax documented here:\n" + "https://www.jooq.org/doc/latest/manual/sql-building/dsl-context/custom-settings/settings-parser/");
        throw e;
    } finally {
        JDBCUtils.safeClose(r);
    }
}
Also used : Scanner(java.util.Scanner) Queries(org.jooq.Queries) ResultQuery(org.jooq.ResultQuery) Query(org.jooq.Query) SQLException(java.sql.SQLException) Matcher(java.util.regex.Matcher) Reader(java.io.Reader) ResultQuery(org.jooq.ResultQuery) DataAccessException(org.jooq.exception.DataAccessException)

Example 32 with Query

use of org.jooq.Query in project jOOQ by jOOQ.

the class DDL method createDomain.

@SuppressWarnings({ "rawtypes", "unchecked" })
final Query createDomain(Domain<?> domain) {
    CreateDomainAsStep s1 = configuration.createDomainIfNotExists() ? ctx.createDomainIfNotExists(domain) : ctx.createDomain(domain);
    CreateDomainDefaultStep s2 = s1.as(domain.getDataType());
    CreateDomainConstraintStep s3 = domain.getDataType().defaulted() ? s2.default_(domain.getDataType().default_()) : s2;
    if (domain.getChecks().isEmpty())
        return s3;
    return s3.constraints(map(domain.getChecks(), c -> c.constraint()));
}
Also used : UniqueKey(org.jooq.UniqueKey) Arrays(java.util.Arrays) Tools.map(org.jooq.impl.Tools.map) KEY_COMP(org.jooq.impl.Comparators.KEY_COMP) Table(org.jooq.Table) SCHEMA(org.jooq.DDLFlag.SCHEMA) SEQUENCE(org.jooq.DDLFlag.SEQUENCE) CreateTableOnCommitStep(org.jooq.CreateTableOnCommitStep) Arrays.asList(java.util.Arrays.asList) Index(org.jooq.Index) DSLContext(org.jooq.DSLContext) Domain(org.jooq.Domain) COMMENT(org.jooq.DDLFlag.COMMENT) DSL.constraint(org.jooq.impl.DSL.constraint) CHECK(org.jooq.DDLFlag.CHECK) Collection(java.util.Collection) Check(org.jooq.Check) Field(org.jooq.Field) Meta(org.jooq.Meta) DOMAIN(org.jooq.DDLFlag.DOMAIN) TableType(org.jooq.TableOptions.TableType) List(java.util.List) Queries(org.jooq.Queries) CreateIndexIncludeStep(org.jooq.CreateIndexIncludeStep) Query(org.jooq.Query) TABLE(org.jooq.DDLFlag.TABLE) ForeignKey(org.jooq.ForeignKey) VIEW(org.jooq.TableOptions.TableType.VIEW) UNIQUE(org.jooq.DDLFlag.UNIQUE) Sequence(org.jooq.Sequence) ArrayList(java.util.ArrayList) CreateViewAsStep(org.jooq.CreateViewAsStep) INDEX(org.jooq.DDLFlag.INDEX) Comment(org.jooq.Comment) Schema(org.jooq.Schema) PRIMARY_KEY(org.jooq.DDLFlag.PRIMARY_KEY) FOREIGN_KEY(org.jooq.DDLFlag.FOREIGN_KEY) NAMED_COMP(org.jooq.impl.Comparators.NAMED_COMP) CreateDomainAsStep(org.jooq.CreateDomainAsStep) DDLFlag(org.jooq.DDLFlag) DDLExportConfiguration(org.jooq.DDLExportConfiguration) OnCommit(org.jooq.TableOptions.OnCommit) CreateSequenceFlagsStep(org.jooq.CreateSequenceFlagsStep) StringUtils(org.jooq.tools.StringUtils) Constraint(org.jooq.Constraint) ConstraintEnforcementStep(org.jooq.ConstraintEnforcementStep) CreateDomainConstraintStep(org.jooq.CreateDomainConstraintStep) Named(org.jooq.Named) TableOptions(org.jooq.TableOptions) CreateDomainDefaultStep(org.jooq.CreateDomainDefaultStep) Key(org.jooq.Key) CreateDomainConstraintStep(org.jooq.CreateDomainConstraintStep) CreateDomainDefaultStep(org.jooq.CreateDomainDefaultStep) CreateDomainAsStep(org.jooq.CreateDomainAsStep)

Example 33 with Query

use of org.jooq.Query in project jOOQ by jOOQ.

the class DDL method createTableOrView.

final List<Query> createTableOrView(Table<?> table, Collection<? extends Constraint> constraints) {
    boolean temporary = table.getTableType() == TableType.TEMPORARY;
    boolean view = table.getTableType().isView();
    OnCommit onCommit = table.getOptions().onCommit();
    if (view) {
        List<Query> result = new ArrayList<>();
        result.add(applyAs((configuration.createViewIfNotExists() ? ctx.createViewIfNotExists(table, table.fields()) : configuration.createOrReplaceView() ? ctx.createOrReplaceView(table, table.fields()) : ctx.createView(table, table.fields())), table.getOptions()));
        if (!constraints.isEmpty() && configuration.includeConstraintsOnViews())
            result.addAll(alterTableAddConstraints(table));
        return result;
    }
    CreateTableOnCommitStep s0 = (configuration.createTableIfNotExists() ? temporary ? ctx.createTemporaryTableIfNotExists(table) : ctx.createTableIfNotExists(table) : temporary ? ctx.createTemporaryTable(table) : ctx.createTable(table)).columns(sortIf(asList(table.fields()), !configuration.respectColumnOrder())).constraints(constraints);
    if (temporary && onCommit != null) {
        switch(onCommit) {
            case DELETE_ROWS:
                return asList(s0.onCommitDeleteRows());
            case PRESERVE_ROWS:
                return asList(s0.onCommitPreserveRows());
            case DROP:
                return asList(s0.onCommitDrop());
            default:
                throw new IllegalStateException("Unsupported flag: " + onCommit);
        }
    }
    return asList(s0);
}
Also used : Query(org.jooq.Query) CreateTableOnCommitStep(org.jooq.CreateTableOnCommitStep) OnCommit(org.jooq.TableOptions.OnCommit) ArrayList(java.util.ArrayList)

Example 34 with Query

use of org.jooq.Query in project Almura by AlmuraDev.

the class ServerStoreManager method handleDelistSellingItems.

public void handleDelistSellingItems(final Player player, final String id, final List<Integer> recNos) {
    checkNotNull(player);
    checkNotNull(id);
    checkNotNull(recNos);
    checkState(!recNos.isEmpty());
    if (!player.hasPermission(Almura.ID + ".store.admin")) {
        this.notificationManager.sendPopupNotification(player, Text.of(TextColors.RED, "Store"), Text.of("You do not have permission " + "to unlist items!"), 5);
        return;
    }
    final Store store = this.getStore(id).orElse(null);
    if (store == null) {
        this.logger.error("Player '{}' attempted to de-list selling items for store '{}' but the server has no knowledge of it. Syncing " + "store registry...", player.getName(), id);
        this.syncStoreRegistryTo(player);
        return;
    }
    final List<SellingItem> sellingItems = store.getSellingItems();
    if (sellingItems.isEmpty()) {
        this.logger.error("Player '{}' attempted to de-list selling items for store '{}' but the server knows of no " + " buying items for it. This could be a de-sync or an exploit.", player.getName(), store.getId());
        this.network.sendTo(player, new ClientboundListItemsResponsePacket(store.getId(), StoreItemSegmentType.SELLING, sellingItems));
        return;
    }
    final List<Integer> copyRecNos = Lists.newArrayList(recNos);
    final Iterator<Integer> iter = copyRecNos.iterator();
    while (iter.hasNext()) {
        final Integer recNo = iter.next();
        final SellingItem found = sellingItems.stream().filter(v -> v.getRecord() == recNo).findAny().orElse(null);
        if (found == null) {
            this.logger.error("Player '{}' attempted to de-list selling item '{}' for store '{}' but the server knows of no knowledge of it. " + "This could be a de-sync or an exploit. Discarding...", player.getName(), recNo, store.getId());
            iter.remove();
        }
    }
    this.scheduler.createTaskBuilder().async().execute(() -> {
        try (final DSLContext context = this.databaseManager.createContext(true)) {
            final List<Query> toUpdate = new ArrayList<>();
            for (final Integer recNo : recNos) {
                toUpdate.add(StoreQueries.createUpdateSellingItemIsHidden(recNo, true).build(context));
            }
            context.batch(toUpdate).execute();
            final Results results = StoreQueries.createFetchSellingItemsAndDataFor(store.getId(), false).build(context).fetchMany();
            final List<SellingItem> finalSellingItems = new ArrayList<>();
            results.forEach(result -> finalSellingItems.addAll(this.parseSellingItemsFrom(result)));
            this.scheduler.createTaskBuilder().execute(() -> {
                store.putSellingItems(finalSellingItems);
                this.network.sendToAll(new ClientboundListItemsResponsePacket(store.getId(), StoreItemSegmentType.SELLING, finalSellingItems));
            }).submit(this.container);
        } catch (final SQLException e) {
            e.printStackTrace();
        }
    }).submit(this.container);
}
Also used : IItemHandler(net.minecraftforge.items.IItemHandler) FilterRegistry(com.almuradev.almura.shared.feature.filter.FilterRegistry) Results(org.jooq.Results) Item(net.minecraft.item.Item) Inject(com.google.inject.Inject) StoreQueries(com.almuradev.almura.feature.store.database.StoreQueries) BuyingItem(com.almuradev.almura.feature.store.listing.BuyingItem) EntityPlayerMP(net.minecraft.entity.player.EntityPlayerMP) DatabaseManager(com.almuradev.almura.shared.database.DatabaseManager) BigDecimal(java.math.BigDecimal) Map(java.util.Map) DSLContext(org.jooq.DSLContext) StoreBuyingItem(com.almuradev.generated.store.tables.StoreBuyingItem) BasicBuyingItem(com.almuradev.almura.feature.store.basic.listing.BasicBuyingItem) NBTTagCompound(net.minecraft.nbt.NBTTagCompound) EconomyService(org.spongepowered.api.service.economy.EconomyService) VanillaStack(com.almuradev.almura.shared.item.VanillaStack) Timestamp(java.sql.Timestamp) ClientboundListItemsResponsePacket(com.almuradev.almura.feature.store.network.ClientboundListItemsResponsePacket) FeatureConstants(com.almuradev.almura.shared.feature.FeatureConstants) Sponge(org.spongepowered.api.Sponge) DatabaseQueue(com.almuradev.almura.shared.database.DatabaseQueue) ServiceManager(org.spongepowered.api.service.ServiceManager) NetworkConfig(com.almuradev.almura.shared.network.NetworkConfig) UUID(java.util.UUID) Result(org.jooq.Result) Instant(java.time.Instant) StoreSellingItemDataRecord(com.almuradev.generated.store.tables.records.StoreSellingItemDataRecord) Collectors(java.util.stream.Collectors) Preconditions.checkState(com.google.common.base.Preconditions.checkState) ClientConnectionEvent(org.spongepowered.api.event.network.ClientConnectionEvent) ChannelBinding(org.spongepowered.api.network.ChannelBinding) List(java.util.List) Stream(java.util.stream.Stream) StoreSellingItemData(com.almuradev.generated.store.tables.StoreSellingItemData) ClientboundStoreGuiResponsePacket(com.almuradev.almura.feature.store.network.ClientboundStoreGuiResponsePacket) CapabilityItemHandler(net.minecraftforge.items.CapabilityItemHandler) StoreSellingItemRecord(com.almuradev.generated.store.tables.records.StoreSellingItemRecord) ChannelId(org.spongepowered.api.network.ChannelId) IngameFeature(com.almuradev.almura.shared.feature.IngameFeature) Optional(java.util.Optional) Player(org.spongepowered.api.entity.living.player.Player) Query(org.jooq.Query) Almura(com.almuradev.almura.Almura) Getter(org.spongepowered.api.event.filter.Getter) StoreBuyingItemData(com.almuradev.generated.store.tables.StoreBuyingItemData) BasicSellingItem(com.almuradev.almura.feature.store.basic.listing.BasicSellingItem) GameStartingServerEvent(org.spongepowered.api.event.game.state.GameStartingServerEvent) HashMap(java.util.HashMap) ServerboundListItemsRequestPacket(com.almuradev.almura.feature.store.network.ServerboundListItemsRequestPacket) Singleton(javax.inject.Singleton) ArrayList(java.util.ArrayList) ItemStack(net.minecraft.item.ItemStack) SQLException(java.sql.SQLException) Lists(com.google.common.collect.Lists) ItemHandlerHelper(net.minecraftforge.items.ItemHandlerHelper) Text(org.spongepowered.api.text.Text) StoreBuyingItemRecord(com.almuradev.generated.store.tables.records.StoreBuyingItemRecord) BasicStore(com.almuradev.almura.feature.store.basic.BasicStore) SellingItem(com.almuradev.almura.feature.store.listing.SellingItem) StoreItem(com.almuradev.almura.feature.store.listing.StoreItem) StoreSellingItem(com.almuradev.generated.store.tables.StoreSellingItem) GameState(org.spongepowered.api.GameState) CauseStackManager(org.spongepowered.api.event.CauseStackManager) PluginContainer(org.spongepowered.api.plugin.PluginContainer) TextColors(org.spongepowered.api.text.format.TextColors) Nullable(javax.annotation.Nullable) Record(org.jooq.Record) StoreBuyingItemDataRecord(com.almuradev.generated.store.tables.records.StoreBuyingItemDataRecord) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) Scheduler(org.spongepowered.api.scheduler.Scheduler) ServerNotificationManager(com.almuradev.almura.feature.notification.ServerNotificationManager) EnumFacing(net.minecraft.util.EnumFacing) IOException(java.io.IOException) SerializationUtil(com.almuradev.almura.shared.util.SerializationUtil) Witness(com.almuradev.core.event.Witness) ClientboundStoresRegistryPacket(com.almuradev.almura.feature.store.network.ClientboundStoresRegistryPacket) ForgeRegistries(net.minecraftforge.fml.common.registry.ForgeRegistries) ResourceLocation(net.minecraft.util.ResourceLocation) Listener(org.spongepowered.api.event.Listener) UniqueAccount(org.spongepowered.api.service.economy.account.UniqueAccount) Comparator(java.util.Comparator) ServerboundModifyItemsPacket(com.almuradev.almura.feature.store.network.ServerboundModifyItemsPacket) SQLException(java.sql.SQLException) BasicStore(com.almuradev.almura.feature.store.basic.BasicStore) ClientboundListItemsResponsePacket(com.almuradev.almura.feature.store.network.ClientboundListItemsResponsePacket) DSLContext(org.jooq.DSLContext) BasicSellingItem(com.almuradev.almura.feature.store.basic.listing.BasicSellingItem) SellingItem(com.almuradev.almura.feature.store.listing.SellingItem) StoreSellingItem(com.almuradev.generated.store.tables.StoreSellingItem) Results(org.jooq.Results) List(java.util.List) ArrayList(java.util.ArrayList)

Example 35 with Query

use of org.jooq.Query in project collect by openforis.

the class JooqRelationalSchemaCreator method createRelationalSchema.

@Override
public void createRelationalSchema(RelationalSchema schema, Connection conn) throws CollectRdbException {
    CollectDSLContext dsl = new CollectDSLContext(conn);
    for (Table<?> table : schema.getTables()) {
        org.jooq.Table<Record> jooqTable = jooqTable(schema, table, !dsl.isSchemaLess());
        CreateTableAsStep<Record> createTableStep = dsl.createTable(jooqTable);
        Query createTableFinalQuery = (Query) createTableStep;
        for (Column<?> column : table.getColumns()) {
            DataType<?> dataType = dsl.getDataType(column.getType().getJavaType());
            Integer length = column.getLength();
            if (length != null) {
                dataType.length(length);
            }
            createTableFinalQuery = createTableStep.column(column.getName(), dataType);
        }
        createTableFinalQuery.execute();
    }
    createDataTableViews(schema, conn);
}
Also used : Query(org.jooq.Query) CollectDSLContext(org.openforis.collect.persistence.jooq.CollectDSLContext) Record(org.jooq.Record)

Aggregations

Query (org.jooq.Query)35 ArrayList (java.util.ArrayList)19 DSLContext (org.jooq.DSLContext)15 Record (org.jooq.Record)11 List (java.util.List)10 ResultQuery (org.jooq.ResultQuery)10 SQLException (java.sql.SQLException)9 Configuration (org.jooq.Configuration)9 Map (java.util.Map)8 BigDecimal (java.math.BigDecimal)6 Timestamp (java.sql.Timestamp)6 Comparator (java.util.Comparator)4 HashMap (java.util.HashMap)4 Constraint (org.jooq.Constraint)4 DDLQuery (org.jooq.DDLQuery)4 Result (org.jooq.Result)4 DSL.constraint (org.jooq.impl.DSL.constraint)4 Almura (com.almuradev.almura.Almura)3 ServerNotificationManager (com.almuradev.almura.feature.notification.ServerNotificationManager)3 BasicStore (com.almuradev.almura.feature.store.basic.BasicStore)3