Debian Codegraph @

docs/scripts/csvsql.rst

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 ======
2 csvsql
3 ======
4
5 Description
6 ===========
7
8 Generate SQL statements for a CSV file or execute those statements directly on a database. In the latter case supports both creating tables and inserting data:
9
10 .. code-block:: none
11
12 usage: csvsql [-h] [-d DELIMITER] [-t] [-q QUOTECHAR] [-u {0,1,2,3}] [-b]
13 [-p ESCAPECHAR] [-z FIELD_SIZE_LIMIT] [-e ENCODING] [-L LOCALE]
14 [-S] [--blanks] [--null-value NULL_VALUES [NULL_VALUES ...]]
15 [--date-format DATE_FORMAT] [--datetime-format DATETIME_FORMAT]
16 [-H] [-K SKIP_LINES] [-v] [-l] [--zero] [-V]
17 [-i {firebird,mssql,mysql,oracle,postgresql,sqlite,sybase}]
18 [--db CONNECTION_STRING] [--query QUERIES] [--insert]
19 [--prefix PREFIX] [--before-insert BEFORE_INSERT]
20 [--after-insert AFTER_INSERT] [--tables TABLE_NAMES]
21 [--no-constraints] [--unique-constraint UNIQUE_CONSTRAINT]
22 [--no-create] [--create-if-not-exists] [--overwrite]
23 [--db-schema DB_SCHEMA] [-y SNIFF_LIMIT] [-I]
24 [--chunk-size CHUNK_SIZE]
25 [FILE [FILE ...]]
26
27 Generate SQL statements for one or more CSV files, or execute those statements
28 directly on a database, and execute one or more SQL queries.
29
30 positional arguments:
31 FILE The CSV file(s) to operate on. If omitted, will accept
32 input as piped data via STDIN.
33
34 optional arguments:
35 -h, --help show this help message and exit
36 -i {mssql,mysql,oracle,postgresql,sqlite,duckdb,crate,ingres}, --dialect {mssql,mysql,oracle,postgresql,sqlite,duckdb,crate,ingres}
37 Dialect of SQL to generate. Cannot be used with --db.
38 --db CONNECTION_STRING
39 If present, a SQLAlchemy connection string to use to
40 directly execute generated SQL on a database.
41 --engine-option ENGINE_OPTION ENGINE_OPTION
42 A keyword argument to SQLAlchemy's create_engine(), as
43 a space-separated pair. This option can be specified
44 multiple times. For example: thick_mode True
45 --query QUERIES Execute one or more SQL queries delimited by --sql-
46 delimiter, and output the result of the last query as
47 CSV. QUERY may be a filename. --query may be specified
48 multiple times.
49 --insert Insert the data into the table. Requires --db.
50 --prefix PREFIX Add an expression following the INSERT keyword, like
51 OR IGNORE or OR REPLACE.
52 --before-insert BEFORE_INSERT
53 Before the INSERT command, execute one or more SQL
54 queries delimited by --sql-delimiter. Requires
55 --insert.
56 --after-insert AFTER_INSERT
57 After the INSERT command, execute one or more SQL
58 queries delimited by --sql-delimiter. Requires
59 --insert.
60 --sql-delimiter SQL_DELIMITER
61 Delimiter separating SQL queries in --query, --before-
62 insert, and --after-insert.
63 --tables TABLE_NAMES A comma-separated list of names of tables to be
64 created. By default, the tables will be named after
65 the filenames without extensions or "stdin".
66 --no-constraints Generate a schema without length limits or null
67 checks. Useful when sampling big tables.
68 --unique-constraint UNIQUE_CONSTRAINT
69 A column-separated list of names of columns to include
70 in a UNIQUE constraint.
71 --no-create Skip creating the table. Requires --insert.
72 --create-if-not-exists
73 Create the table if it does not exist, otherwise keep
74 going. Requires --insert.
75 --overwrite Drop the table if it already exists. Requires
76 --insert. Cannot be used with --no-create.
77 --db-schema DB_SCHEMA
78 Optional name of database schema to create table(s)
79 in.
80 -y SNIFF_LIMIT, --snifflimit SNIFF_LIMIT
81 Limit CSV dialect sniffing to the specified number of
82 bytes. Specify "0" to disable sniffing entirely, or
83 "-1" to sniff the entire file.
84 -I, --no-inference Disable type inference (and --locale, --date-format,
85 --datetime-format, --no-leading-zeroes) when parsing
86 the input.
87 --chunk-size CHUNK_SIZE
88 Chunk size for batch insert into the table. Requires
89 --insert.
90 --min-col-len MIN_COL_LEN
91 The minimum length of text columns.
92 --col-len-multiplier COL_LEN_MULTIPLIER
93 Multiply the maximum column length by this multiplier
94 to accomodate larger values in later runs.
95
96
97 See also: :doc:`../common_arguments`.
98
99 For information on connection strings and supported dialects refer to the `SQLAlchemy documentation <https://www.sqlalchemy.org/docs/dialects/>`_.
100
101 If you prefer not to enter your password in the connection string, store the password securely in a `PostgreSQL Password File <https://www.postgresql.org/docs/9.1/static/libpq-pgpass.html>`_, a `MySQL Options File <https://dev.mysql.com/doc/refman/5.7/en/option-files.html>`_ or similar files for other systems.
102
103 .. note::
104
105 Using the :code:`--query` option may cause rounding (in Python 2) or introduce `Python floating point issues <https://docs.python.org/3/tutorial/floatingpoint.html>`_ (in Python 3).
106
107 .. note::
108
109 If the CSV file was created from a JSON file using :doc:`in2csv`, remember to quote SQL columns properly. For example:
110
111 .. code-block:: bash
112
113 echo '{"a":{"b":"c"},"d":"e"}' | in2csv -f ndjson | csvsql --query 'SELECT "a/b" FROM stdin'
114
115 .. note::
116
117 Alternatives to :doc:`csvsql` are `q <https://github.com/harelba/q>`_ and `textql <https://github.com/dinedal/textql>`_.
118
119 Examples
120 ========
121
122 Generate SQL statements
123 -----------------------
124
125 Generate a statement in the PostgreSQL dialect:
126
127 .. code-block:: bash
128
129 csvsql -i postgresql examples/realdata/FY09_EDU_Recipients_by_State.csv
130
131 Interact with a SQL database
132 ----------------------------
133
134 Create a table and import data from the CSV directly into PostgreSQL:
135
136 .. code-block:: bash
137
138 createdb test
139 csvsql --db postgresql:///test --tables fy09 --insert examples/realdata/FY09_EDU_Recipients_by_State.csv
140
141 For large tables it may not be practical to process the entire table. One solution to this is to analyze a sample of the table. In this case it can be useful to turn off length limits and null checks with the :code:`--no-constraints` option:
142
143 .. code-block:: bash
144
145 head -n 20 examples/realdata/FY09_EDU_Recipients_by_State.csv | csvsql --no-constraints --tables fy09
146
147 Create tables for an entire directory of CSVs and import data from those files directly into PostgreSQL:
148
149 .. code-block:: bash
150
151 createdb test
152 csvsql --db postgresql:///test --insert examples/*_converted.csv
153
154 If those CSVs have identical headers, you can import them into the same table by using :doc:`csvstack` first:
155
156 .. code-block:: bash
157
158 createdb test
159 csvstack examples/dummy?.csv | csvsql --db postgresql:///test --insert
160
161 Query and output CSV files using SQL
162 ------------------------------------
163
164 You can use csvsql to "directly" query one or more CSV files. Please note that this will create an in-memory SQLite database, so it won't be very fast:
165
166 .. code-block:: bash
167
168 csvsql --query "SELECT m.usda_id, avg(i.sepal_length) AS mean_sepal_length FROM iris AS i JOIN irismeta AS m ON (i.species = m.species) GROUP BY m.species" examples/iris.csv examples/irismeta.csv
169
170 Group rows by one column:
171
172 .. code-block:: bash
173
174 csvsql --query "SELECT * FROM 'dummy3' GROUP BY a" examples/dummy3.csv
175
176 Concatenate two columns:
177
178 .. code-block:: bash
179
180 csvsql --query "SELECT a || b FROM 'dummy3'" --no-inference examples/dummy3.csv
181
182 If a column contains null values, you must ``COALESCE`` the column:
183
184 .. code-block:: bash
185
186 csvsql --query "SELECT a || COALESCE(b, '') FROM 'sort_ints_nulls'" --no-inference examples/sort_ints_nulls.csv
187
188 The ``UPDATE`` SQL statement produces no output. Remember to ``SELECT`` the columns and rows you want:
189
190 .. code-block:: bash
191
192 csvsql --query "UPDATE 'dummy3' SET a = 'foo'; SELECT * FROM 'dummy3'" examples/dummy3.csv