Where to store SQL commands for execution

后端 未结 12 1687
后悔当初
后悔当初 2021-02-05 16:00

We face code quality issues because of inline mysql queries. Having self-written mysql queries really clutters the code and also increases code base etc.

Our code is clu

12条回答
  •  感动是毒
    2021-02-05 16:44

    I'm late to the party, but if you want to store related queries in a single file, YAML is a good fit because it handles arbitrary whitespace better than pretty much any other data serialization format, and it has some other nice features like comments:

    someQuery: |-
      SELECT *
       ,DATE_ADD(sc.created_at,INTERVAL 14 DAY) AS duedate
       ,distance_mail(?,?,lat,lon) as distance,count(pks.skill_id) c1
       ,count(ps.profile_id) c2
        FROM TABLE sc
        -- ...
    
    # Here's a comment explaining the following query
    someOtherQuery: |-
      SELECT 1;
    

    This way, using a module like js-yaml you can easily load all of the queries into an object at startup and access each by a sensible name:

    const fs = require('fs');
    const jsyaml = require('js-yaml');
    export default jsyaml.load(fs.readFileSync('queries.yml'));
    

    Here's a snippet of it in action (using a template string instead of a file):

    const yml =
    `someQuery: |-
      SELECT *
        FROM TABLE sc;
    someOtherQuery: |-
      SELECT 1;`;
    
    const queries = jsyaml.load(yml);
    console.dir(queries);
    console.log(queries.someQuery);

提交回复
热议问题