Created
          May 9, 2018 14:21 
        
      - 
      
 - 
        
Save mgiacomini/944dc6bede7ae2e5390a54129998852b to your computer and use it in GitHub Desktop.  
    export query for ecto
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | def build_export_query(user, batch_size \\ 500) | |
| columns = ~w(id name amount amount_currency cycle first_bill_date type type_description) | |
| query = """ | |
| COPY ( | |
| SELECT #{Enum.join(columns, ",")} | |
| FROM subscriptions | |
| WHERE archived = false | |
| AND user_id = #{user.id} | |
| ) to STDOUT WITH CSV DELIMITER ','; | |
| """ | |
| csv_header = [Enum.join(columns, ","), "\n"] | |
| Ecto.Adapters.SQL.stream(Repo, query, [], max_rows: batch_size) | |
| |> Stream.map(&(&1.rows)) | |
| |> (fn stream -> Stream.concat(csv_header, stream) end).() | |
| end | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment