Keyword only arguments for transform()

Also renamed columns= to types=

Closes #165
This commit is contained in:
Simon Willison 2020-09-21 23:39:10 -07:00 committed by GitHub
commit f8e10df00e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 11 additions and 9 deletions

View file

@ -926,12 +926,12 @@ The ``table.transform()`` method can do all of these things, by implementing a m
The ``.transform()`` method takes a number of parameters, all of which are optional.
To alter the type of a column, use the first argument:
To alter the type of a column, use the ``types=`` argument:
.. code-block:: python
# Convert the 'age' column to an integer, and 'weight' to a float
table.transform({"age": int, "weight": float})
table.transform(types={"age": int, "weight": float})
The ``rename=`` parameter can rename columns:

View file

@ -718,7 +718,8 @@ class Table(Queryable):
def transform(
self,
columns=None,
*,
types=None,
rename=None,
drop=None,
pk=DEFAULT,
@ -728,7 +729,7 @@ class Table(Queryable):
):
assert self.exists(), "Cannot transform a table that doesn't exist yet"
sqls = self.transform_sql(
columns=columns,
types=types,
rename=rename,
drop=None,
pk=pk,
@ -754,7 +755,8 @@ class Table(Queryable):
def transform_sql(
self,
columns=None,
*,
types=None,
rename=None,
drop=None,
pk=DEFAULT,
@ -763,7 +765,7 @@ class Table(Queryable):
drop_foreign_keys=None,
tmp_suffix=None,
):
columns = columns or {}
types = types or {}
rename = rename or {}
drop = drop or set()
new_table_name = "{}_new_{}".format(
@ -773,7 +775,7 @@ class Table(Queryable):
new_column_pairs = []
copy_from_to = {column: column for column, _ in current_column_pairs}
for name, type_ in current_column_pairs:
type_ = columns.get(name) or type_
type_ = types.get(name) or type_
if name in drop:
del [copy_from_to[name]]
continue

View file

@ -18,7 +18,7 @@ import pytest
),
# Change column type
(
{"columns": {"age": int}},
{"types": {"age": int}},
[
"CREATE TABLE [dogs_new_suffix] (\n [id] INTEGER PRIMARY KEY,\n [name] TEXT,\n [age] INTEGER\n);",
"INSERT INTO [dogs_new_suffix] ([id], [name], [age]) SELECT [id], [name], [age] FROM [dogs]",
@ -48,7 +48,7 @@ import pytest
),
# Convert type AND rename column
(
{"columns": {"age": int}, "rename": {"age": "dog_age"}},
{"types": {"age": int}, "rename": {"age": "dog_age"}},
[
"CREATE TABLE [dogs_new_suffix] (\n [id] INTEGER PRIMARY KEY,\n [name] TEXT,\n [dog_age] INTEGER\n);",
"INSERT INTO [dogs_new_suffix] ([id], [name], [dog_age]) SELECT [id], [name], [age] FROM [dogs]",