Skip to content

Let UPDATE, INSERT and DELETE work on data passed in parameter. #348

Open

Description

@pasapsi
alasql('update ? as kpi_table set kpi_table.owner->selected = ? where kpi_table.owner.id=?', [[{id: 1, name: 'text', selected: true}, {id: 2, name: 'text2', selected: false}], false, 1])

Activity

  1. mathiasrw commented on Jul 2, 2015

    @mathiasrw
    Member

    Can you elaborate on the problem?

  2. agershun commented on Jul 2, 2015

    @agershun
    Member

    ? in UPDATE is not currently supported. We can add this if it is required.

  3. agershun commented on Jul 2, 2015

    @agershun
    Member

    Do we need the same for INSERT and DELETE?

  4. pasapsi commented on Jul 2, 2015

    @pasapsi
    Author

    hard to say, I'm just as solutions to their problems find various inconveniences in the library

  5. pasapsi commented on Jul 2, 2015

    @pasapsi
    Author

    @mathiasrw

    The problem is that I can not update the data in the structure :(, based on the rules of writing a request for mysql or mssql

  6. agershun commented on Jul 2, 2015

    @agershun
    Member

    I will try to see can we implement ? in INSERT/DELETE/UPDATE statements.

  7. agershun commented on Jul 2, 2015

    @agershun
    Member

    The syntax can be:

        alasql('INSERT INTO ? (...) VALUES ...',[data]);
        alasql('UPDATE ? SET ... WHERE ...',[data]);
        alasql('DELETE FROM ? WHERE ...',[data]);
  8. pasapsi commented on Jul 2, 2015

    @pasapsi
    Author

    cool, change object occurs on the link?

  9. pasapsi commented on Jul 2, 2015

    @pasapsi
    Author

    Sample

    var data = [{id: 1, text: 'test'}]
    alasql('INSERT INTO ? (id, text) VALUES (2, "test 2")',[data]);
    
    data =====> [{id: 1, text: 'test'}, {id: 2, text: 'test 2'}]
    

    OR

    var data = [{id: 1, text: 'test'}]
    var res = alasql('INSERT INTO ? (id, text) VALUES (2, "test 2")',[data]);
    
    data =====> [{id: 1, text: 'test'}]
    res =====> [{id: 1, text: 'test'}, {id: 2, text: 'test 2'}]
    
  10. agershun commented on Jul 2, 2015

    @agershun
    Member

    The first option. The res for the first case will be 1 (only one record was inserted).

    I will try to program this tonight.

  11. pasapsi commented on Jul 2, 2015

    @pasapsi
    Author

    Thank you for such a library as alasql 👍

  12. agershun commented on Jul 2, 2015

    @agershun
    Member

    Probably, we do not need INSERT INTO ? because it easier to use:

        data.push(obj);

    :) But for UPDATE and DELETE it can have sense.

  13. pasapsi commented on Jul 2, 2015

    @pasapsi
    Author

    Perhaps, but what to do if you want to implement such a request?

    INSERT INTO
        `some_table` (`fld1`,`fld2`,`fld3`)
    SELECT
        `src`.`fld1`,
        `src`.`fld2`,
        `src`.`fld3` 
    FROM
        `some_table`  AS `src`
    WHERE
        `src`.`fld` > 100;
    
  14. agershun commented on Jul 2, 2015

    @agershun
    Member

    This particular query already works.

    But for parameter data:

        alasql('INSERT INTO ? (a) SELECT * FROM one',[data]);
  15. 13 remaining items

  16. mathiasrw commented on Mar 2, 2017

    @mathiasrw
    Member

    SELECT is already supported:

    var data = [{a:1,b:10}, {a:2,b:20}, {a:1,b:30}];
    
    var res = alasql('SELECT a, SUM(b) AS b FROM ? GROUP BY a',[data]);    
    
    console.log(res); // [{"a":1,"b":40},{"a":2,"b":20}]
  17. jiron12 commented on Mar 2, 2017

    @jiron12

    No I'm talking about something more like this:

    var data = [
      {fistname: "John", lastname: "Doe", state: "New York", birthdate: "1979-09-12"},
      {fistname: "John", lastname: "Doe", state: "Wisconsin", birthdate: "1964-03-02"},
      {fistname: "John", lastname: "Doe", state: "Wisconsin", birthdate: "1975-05-19"}
    ];
    
    alasql('CREATE TABLE test');
    alasql('INSERT INTO test SELECT * FROM ?', [data]);
    alasql('SELECT * FROM test', [[{fistname: "John", lastname: "Doe", state: "Wisconsin"}]]);
    
    console.log(res); // [
      {fistname: "John", lastname: "Doe", state: "Wisconsin", birthdate: "1964-03-02"},
      {fistname: "John", lastname: "Doe", state: "Wisconsin", birthdate: "1975-05-19"}
    ]
    
  18. matt212 commented on Jun 2, 2018

    @matt212

    Hi,
    i am using current version of alasql 0.4.5
    i am unable to perform update on json array
    js fiddle url:
    alasql update jsfiddle

    error:-
    aa

    what is proper way to update jsonarray using alasql !

  19. mathiasrw commented on Jun 2, 2018

    @mathiasrw
    Member

    I get this when clicking on the link

    Error 404
    We're truly sorry, but there is no such page.
    
  20. matt212 commented on Jun 6, 2018

    @matt212

    @mathiasrw sorry , i edited my post with valid jsfiddle url please check now
    FYI:
    update reference link

  21. mathiasrw commented on Jun 6, 2018

    @mathiasrw
    Member

    i am unable to perform update on json array

    This issue (#348) is still open because this is still a feature request

  22. matt212 commented on Jun 7, 2018

    @matt212

    @mathiasrw ,

    current workaround for time being
    jsfiddle url:
    updated workaround

    alasql('CREATE TABLE one');
    alasql.tables.one.data = data;
    var datasets=alasql('update one SET key=? WHERE inputtype=?;select * from one; truncate table one',['accesstypeaaaaa','multiselect']);
    
    console.log(datasets[1])
    /*check if table is truncated */
    var red=alasql('select * from one')
    console.log(red)
    
    
  23. rtxu commented on Sep 23, 2019

    @rtxu

    Voted up on FeatHub

  24. jhvissotto commented on Mar 17, 2020

    @jhvissotto

    I have the same problem!

  25. Danilo-Araujo-Silva commented on Jan 9, 2021

    @Danilo-Araujo-Silva

    Please add this ;)

  26. syonfox commented on Mar 31, 2021

    @syonfox

    correct me if im working but what we need is a pg format function that runs in the browser https://github.com/datalanche/node-pg-format
    this is a node app but it have dependencies and just needs to be copied into a file see bellow. and then we can do this

    let stmt = format(`UPDATE %I SET (%I) = (%L) WHERE %I.%I = %L RETURNING *`, this.table, keys, values, this.table, key, value);
    alasql(stmt, [data]);
    
    

    ... i realize this is not right now haha guna leave this here anyway :) might help someone +1 for update support

    format.js
    'use strict';
    //
    // PostgreSQL reserved words
    //
    
    // reserved Postgres words
    var reservedMap = {
        "AES128": true,
        "AES256": true,
        "ALL": true,
        "ALLOWOVERWRITE": true,
        "ANALYSE": true,
        "ANALYZE": true,
        "AND": true,
        "ANY": true,
        "ARRAY": true,
        "AS": true,
        "ASC": true,
        "AUTHORIZATION": true,
        "BACKUP": true,
        "BETWEEN": true,
        "BINARY": true,
        "BLANKSASNULL": true,
        "BOTH": true,
        "BYTEDICT": true,
        "CASE": true,
        "CAST": true,
        "CHECK": true,
        "COLLATE": true,
        "COLUMN": true,
        "CONSTRAINT": true,
        "CREATE": true,
        "CREDENTIALS": true,
        "CROSS": true,
        "CURRENT_DATE": true,
        "CURRENT_TIME": true,
        "CURRENT_TIMESTAMP": true,
        "CURRENT_USER": true,
        "CURRENT_USER_ID": true,
        "DEFAULT": true,
        "DEFERRABLE": true,
        "DEFLATE": true,
        "DEFRAG": true,
        "DELTA": true,
        "DELTA32K": true,
        "DESC": true,
        "DISABLE": true,
        "DISTINCT": true,
        "DO": true,
        "ELSE": true,
        "EMPTYASNULL": true,
        "ENABLE": true,
        "ENCODE": true,
        "ENCRYPT": true,
        "ENCRYPTION": true,
        "END": true,
        "EXCEPT": true,
        "EXPLICIT": true,
        "FALSE": true,
        "FOR": true,
        "FOREIGN": true,
        "FREEZE": true,
        "FROM": true,
        "FULL": true,
        "GLOBALDICT256": true,
        "GLOBALDICT64K": true,
        "GRANT": true,
        "GROUP": true,
        "GZIP": true,
        "HAVING": true,
        "IDENTITY": true,
        "IGNORE": true,
        "ILIKE": true,
        "IN": true,
        "INITIALLY": true,
        "INNER": true,
        "INTERSECT": true,
        "INTO": true,
        "IS": true,
        "ISNULL": true,
        "JOIN": true,
        "LEADING": true,
        "LEFT": true,
        "LIKE": true,
        "LIMIT": true,
        "LOCALTIME": true,
        "LOCALTIMESTAMP": true,
        "LUN": true,
        "LUNS": true,
        "LZO": true,
        "LZOP": true,
        "MINUS": true,
        "MOSTLY13": true,
        "MOSTLY32": true,
        "MOSTLY8": true,
        "NATURAL": true,
        "NEW": true,
        "NOT": true,
        "NOTNULL": true,
        "NULL": true,
        "NULLS": true,
        "OFF": true,
        "OFFLINE": true,
        "OFFSET": true,
        "OLD": true,
        "ON": true,
        "ONLY": true,
        "OPEN": true,
        "OR": true,
        "ORDER": true,
        "OUTER": true,
        "OVERLAPS": true,
        "PARALLEL": true,
        "PARTITION": true,
        "PERCENT": true,
        "PLACING": true,
        "PRIMARY": true,
        "RAW": true,
        "READRATIO": true,
        "RECOVER": true,
        "REFERENCES": true,
        "REJECTLOG": true,
        "RESORT": true,
        "RESTORE": true,
        "RIGHT": true,
        "SELECT": true,
        "SESSION_USER": true,
        "SIMILAR": true,
        "SOME": true,
        "SYSDATE": true,
        "SYSTEM": true,
        "TABLE": true,
        "TAG": true,
        "TDES": true,
        "TEXT255": true,
        "TEXT32K": true,
        "THEN": true,
        "TO": true,
        "TOP": true,
        "TRAILING": true,
        "TRUE": true,
        "TRUNCATECOLUMNS": true,
        "UNION": true,
        "UNIQUE": true,
        "USER": true,
        "USING": true,
        "VERBOSE": true,
        "WALLET": true,
        "WHEN": true,
        "WHERE": true,
        "WITH": true,
        "WITHOUT": true,
    };
    
    var fmtPattern = {
        ident: 'I',
        literal: 'L',
        string: 's',
    };
    
    // convert to Postgres default ISO 8601 format
    function formatDate(date) {
        date = date.replace('T', ' ');
        date = date.replace('Z', '+00');
        return date;
    }
    
    function isReserved(value) {
        if (reservedMap[value.toUpperCase()]) {
            return true;
        }
        return false;
    }
    
    function arrayToList(useSpace, array, formatter) {
        var sql = '';
        var temp = [];
    
        sql += useSpace ? ' (' : '(';
        for (var i = 0; i < array.length; i++) {
            sql += (i === 0 ? '' : ', ') + formatter(array[i]);
        }
        sql += ')';
    
        return sql;
    }
    
    // Ported from PostgreSQL 9.2.4 source code in src/interfaces/libpq/fe-exec.c
    function quoteIdent(value) {
    
        if (value === undefined || value === null) {
            throw new Error('SQL identifier cannot be null or undefined');
        } else if (value === false) {
            return '"f"';
        } else if (value === true) {
            return '"t"';
        } else if (value instanceof Date) {
            return '"' + formatDate(value.toISOString()) + '"';
        } else if (value instanceof Buffer) {
            throw new Error('SQL identifier cannot be a buffer');
        } else if (Array.isArray(value) === true) {
            var temp = [];
            for (var i = 0; i < value.length; i++) {
                if (Array.isArray(value[i]) === true) {
                    throw new Error('Nested array to grouped list conversion is not supported for SQL identifier');
                } else {
                    temp.push(quoteIdent(value[i]));
                }
            }
            return temp.toString();
        } else if (value === Object(value)) {
            throw new Error('SQL identifier cannot be an object');
        }
    
        var ident = value.toString().slice(0); // create copy
    
        // do not quote a valid, unquoted identifier
        if (/^[a-z_][a-z0-9_$]*$/.test(ident) === true && isReserved(ident) === false) {
            return ident;
        }
    
        var quoted = '"';
    
        for (var i = 0; i < ident.length; i++) {
            var c = ident[i];
            if (c === '"') {
                quoted += c + c;
            } else {
                quoted += c;
            }
        }
    
        quoted += '"';
    
        return quoted;
    };
    
    // Ported from PostgreSQL 9.2.4 source code in src/interfaces/libpq/fe-exec.c
    function quoteLiteral(value) {
    
        var literal = null;
        var explicitCast = null;
    
        if (value === undefined || value === null) {
            return 'NULL';
        } else if (value === false) {
            return "'f'";
        } else if (value === true) {
            return "'t'";
        } else if (value instanceof Date) {
            return "'" + formatDate(value.toISOString()) + "'";
        } else if (value instanceof Buffer) {
            return "E'\\\\x" + value.toString('hex') + "'";
        } else if (Array.isArray(value) === true) {
            var temp = [];
            for (var i = 0; i < value.length; i++) {
                if (Array.isArray(value[i]) === true) {
                    temp.push(arrayToList(i !== 0, value[i], quoteLiteral))
                } else {
                    temp.push(quoteLiteral(value[i]));
                }
            }
            return temp.toString();
        } else if (value === Object(value)) {
            explicitCast = 'jsonb';
            literal = JSON.stringify(value);
        } else {
            literal = value.toString().slice(0); // create copy
        }
    
        var hasBackslash = false;
        var quoted = '\'';
    
        for (var i = 0; i < literal.length; i++) {
            var c = literal[i];
            if (c === '\'') {
                quoted += c + c;
            } else if (c === '\\') {
                quoted += c + c;
                hasBackslash = true;
            } else {
                quoted += c;
            }
        }
    
        quoted += '\'';
    
        if (hasBackslash === true) {
            quoted = 'E' + quoted;
        }
    
        if (explicitCast) {
            quoted += '::' + explicitCast;
        }
    
        return quoted;
    };
    
    function quoteString(value) {
    
        if (value === undefined || value === null) {
            return '';
        } else if (value === false) {
            return 'f';
        } else if (value === true) {
            return 't';
        } else if (value instanceof Date) {
            return formatDate(value.toISOString());
        } else if (value instanceof Buffer) {
            return '\\x' + value.toString('hex');
        } else if (Array.isArray(value) === true) {
            var temp = [];
            for (var i = 0; i < value.length; i++) {
                if (value[i] !== null && value[i] !== undefined) {
                    if (Array.isArray(value[i]) === true) {
                        temp.push(arrayToList(i !== 0, value[i], quoteString));
                    } else {
                        temp.push(quoteString(value[i]));
                    }
                }
            }
            return temp.toString();
        } else if (value === Object(value)) {
            return JSON.stringify(value);
        }
    
        return value.toString().slice(0); // return copy
    }
    
    function config(cfg) {
    
        // default
        fmtPattern.ident = 'I';
        fmtPattern.literal = 'L';
        fmtPattern.string = 's';
    
        if (cfg && cfg.pattern) {
            if (cfg.pattern.ident) {
                fmtPattern.ident = cfg.pattern.ident;
            }
            if (cfg.pattern.literal) {
                fmtPattern.literal = cfg.pattern.literal;
            }
            if (cfg.pattern.string) {
                fmtPattern.string = cfg.pattern.string;
            }
        }
    }
    
    function formatWithArray(fmt, parameters) {
    
        var index = 0;
        var params = parameters;
    
        var re = '%(%|(\\d+\\$)?[';
        re += fmtPattern.ident;
        re += fmtPattern.literal;
        re += fmtPattern.string;
        re += '])';
        re = new RegExp(re, 'g');
    
        return fmt.replace(re, function (_, type) {
    
            if (type === '%') {
                return '%';
            }
    
            var position = index;
            var tokens = type.split('$');
    
            if (tokens.length > 1) {
                position = parseInt(tokens[0]) - 1;
                type = tokens[1];
            }
    
            if (position < 0) {
                throw new Error('specified argument 0 but arguments start at 1');
            } else if (position > params.length - 1) {
                throw new Error('too few arguments');
            }
    
            index = position + 1;
    
            if (type === fmtPattern.ident) {
                return quoteIdent(params[position]);
            } else if (type === fmtPattern.literal) {
                return quoteLiteral(params[position]);
            } else if (type === fmtPattern.string) {
                return quoteString(params[position]);
            }
        });
    }
    
    function format(fmt) {
        var args = Array.prototype.slice.call(arguments);
        args = args.slice(1); // first argument is fmt
        return formatWithArray(fmt, args);
    }
    
    /*
    exports = module.exports = format;
    exports.config = config;
    exports.ident = quoteIdent;
    exports.literal = quoteLiteral;
    exports.string = quoteString;
    exports.withArray = formatWithArray;
    */
    
  27. added this to the Focus milestone on Oct 14, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions