Convenient way to wrap long SQL statements in javascript

前端 未结 5 1500
别那么骄傲
别那么骄傲 2021-01-26 09:35

In python, one can use \"\"\" to wrap long MySQL statements. For example,

sql = \"\"\"CREATE TABLE EMPLOYEE (
         FIRST_NAME  CHAR(20) NOT NULL,
         L         


        
5条回答
  •  时光取名叫无心
    2021-01-26 10:11

    In this answer, I suggest staging your multi-line string via a string array. Then, once the staging is complete you finalize the multi-line string by using join to enforce lines are separated with a newline character.

    In Sumukh Barve's answer, the strings were carefully constructed with a whitespace character separator (instead of a newline character). In itself, it's not wrong, however, it could lead to malformed SQL statements. When maintaining such SQL statements, the maintainer could easily overlook the need for the whitespace character and could inadvertently malformed the SQL statement:

    "CREATE TABLE" +
    "EMPLOYEE (" + //...
    

    Would result in:

    "CREATE TABLEEMPLOYEE (" + //...
    

    The use of join can also help ensure that there is a mandatory newline character separating the lines without the need to remember to add it within the text of each line.

    [ "CREATE TABLE",
      "EMPLOYEE (" ].join("\n")
    

    Would result in:

    CREATE TABLE
    EMPLOYEE (
    

    Without a newline character, all errors will be reported on line 1. For example, on PSQL:

    CREATE TABLE EMP (ID);
    

    Would report:

    ERROR:  syntax error at or near ";"
    LINE 1: TABLE EMP(ID);
    

    Regardless of how long the SQL statement is, all errors will be reported against LINE 1.

    However, if a new line was added, e.g.

    CREATE TABLE EMP (
        ID);
    

    You will get better feedback on which line caused the error:

    ERROR:  syntax error at or near ";"
    LINE 2: ID);
    

    Also using join with the newline character aids in logging.

    Note that there is an implicit newline separator present in @user781486 answer because of the ES6 backtick notation. ES6 backtick notation looks simple. However, it rapidly loses it's simplicity when you decide to mix backtick notation with conditional business rules.

    Your mileage may vary.

    function buildSQL(includeAge) {
      let arr = [];
      arr.push( "CREATE TABLE EMPLOYEE (" );
      arr.push( "    FIRST_NAME  CHAR(20) NOT NULL," );
      arr.push( "    LAST_NAME   CHAR(20), " );
      if (includeAge) {
          arr.push( "    AGE         INT," );
      }
      arr.push( "    SEX         CHAR(1)," );
      arr.push( "    INCOME      FLOAT " );
      arr.push( "); " );
      let sql = arr.join("\n");
      return sql;
    }
    
    function refreshSQL() {
      let includeAge = $("#includeAge").is(':checked');
      let sql = buildSQL(includeAge);
      $("#resultSQL").val(sql);
    }
    
    $("#includeAge").on('change', refreshSQL);
    
    refreshSQL();
    
    
    

提交回复
热议问题