GithubHelp home page GithubHelp logo

Modify column SQL select about graphile-engine HOT 1 CLOSED

Tam avatar Tam commented on June 2, 2024
Modify column SQL select

from graphile-engine.

Comments (1)

Tam avatar Tam commented on June 2, 2024 1

After some hints from @benjie and @RedShift1 on Discord and even more digging into the source, I've managed to get the following working (even if it's the opposite of @benjie's suggestion 😅):

module.exports = function i18nPlugin (builder) {
    const isPrimaryKey = (table, attr) => table.primaryKeyConstraint && table.primaryKeyConstraint.keyAttributeNums.includes(attr.num)
        , isForeignKey = (table, attr) => table.constraints.some(constraint => constraint.type === 'f' && constraint.keyAttributeNums.includes(attr.num));

    builder.hook('GraphQLObjectType:fields', (
        fields,
        build,
        context,
    ) => {
        const {
            pgSql: sql, inflection, pgColumnFilter, pgOmit: omit,
            graphql: { GraphQLString },
            pgGetSelectValueForFieldAndTypeAndModifier,
        } = build;
        const { scope, fieldWithHooks } = context;

        const { pgIntrospection: table, isPgRowType, isPgCompoundType } = scope;

        // Ensure we're only working on tables
        if (!(isPgRowType || isPgCompoundType) || !table || table.kind !== 'class')
            return fields;

        // Filter out any fields we don't want to work with
        const attributesToReplace = table.attributes
            .filter(a => !(                       // Filter out if any are true:
                   !a.tags.i18n                       // Isn't translatable
                || !pgColumnFilter(a, build, context) // Isn't whatever this is
                || omit(a, 'read')                    // Isn't readable
                || isPrimaryKey(table, a)             // Is a primary key
                || isForeignKey(table, a)             // Is a foreign key
            ));

        if (attributesToReplace.length === 0)
            return fields;

        const keyPrefix = `${table.namespace.name}.${table.name}`;

        for (const attr of attributesToReplace) {
            const fieldName = inflection.column(attr);

            // Replace the existing field with a modified version of itself
            fields[fieldName] = fieldWithHooks(
                fieldName,
                fieldContext => {
                    const { addDataGenerator } = fieldContext;
                    const column = sql.identifier(attr.name);
                    const key = `${keyPrefix}.${column.names.join('.')}`;

                    addDataGenerator(parsedResolveInfoFragment => ({
                        pgQuery: queryBuilder => {
                            const tableAlias = queryBuilder.getTableAlias();

                            // Note: You shouldn't modify `queryBuilder.data`
                            // directly, but we're doing it anyway
                            // @see https://github.com/graphile/graphile-engine/issues/368#issuecomment-450865101

                            // Filter out the existing select for this column
                            // by its alias...
                            queryBuilder.data.select = queryBuilder.data.select
                                .filter(s => s[1] !== parsedResolveInfoFragment.alias);

                            // ...and add our select in its place
                            queryBuilder.select(
                                pgGetSelectValueForFieldAndTypeAndModifier(
                                    GraphQLString,
                                    fieldContext,
                                    parsedResolveInfoFragment,
                                    sql.fragment`(coalesce((
                                      select pairs 
                                        from ${sql.identifier('internal', 'i18n_pairs')} 
                                       where id = ${tableAlias}.${sql.identifier('id')} 
                                         and locale = util.preferred_locale()
                                    )->>'${sql.raw(key)}', ${column}))`,
                                    attr.type,
                                    attr.typeModifier
                                ),
                                parsedResolveInfoFragment.alias
                            );
                        },
                    }));

                    // Since we're not actually changing anything about the
                    // field (just how it's queried) we can return it like
                    // nothing happened...
                    return fields[fieldName];
                },
                { pgFieldIntrospection: attr },
            );
        }

        return fields;
    }, ['PgColumns']);
};

While it does exactly what I want it to, it does have one major flaw. For each column we want to translate, we're having to do a sub-query to get the translated values. It would be much more performant to join the table instead. Unfortunately this isn't possible at the moment (see #368 (comment) and #2) even if we abuse queryBuilder.data.join (which adds it to the sub-query with no way of selecting columns).

Since it's working I'm going to close this issue for now, but might come back to it if we notice any significant performance issues.

from graphile-engine.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.