mirror of
https://github.com/simonw/sqlite-utils.git
synced 2026-07-23 01:14:31 +02:00
table.duplicate(new_table_name) feature, closes #449
Thanks, @davidleejy
This commit is contained in:
parent
42440d6345
commit
b366e68deb
2 changed files with 51 additions and 0 deletions
|
|
@ -1476,6 +1476,21 @@ class Table(Queryable):
|
|||
)
|
||||
return self
|
||||
|
||||
def duplicate(self, name_new: str) -> "Table":
|
||||
"""
|
||||
Duplicate this table in this database.
|
||||
|
||||
:param name_new: Name of new table.
|
||||
"""
|
||||
assert self.exists()
|
||||
with self.db.conn:
|
||||
sql = "CREATE TABLE [{new_table}] AS SELECT * FROM [{table}];".format(
|
||||
new_table=name_new,
|
||||
table=self.name,
|
||||
)
|
||||
self.db.execute(sql)
|
||||
return self.db[name_new]
|
||||
|
||||
def transform(
|
||||
self,
|
||||
*,
|
||||
|
|
|
|||
36
tests/test_duplicate.py
Normal file
36
tests/test_duplicate.py
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
import datetime
|
||||
|
||||
|
||||
def test_duplicate(fresh_db):
|
||||
# Create table using native Sqlite statement:
|
||||
fresh_db.execute(
|
||||
"""CREATE TABLE [table1] (
|
||||
[text_col] TEXT,
|
||||
[real_col] REAL,
|
||||
[int_col] INTEGER,
|
||||
[bool_col] INTEGER,
|
||||
[datetime_col] TEXT)"""
|
||||
)
|
||||
# Insert one row of mock data:
|
||||
dt = datetime.datetime.now()
|
||||
data = {
|
||||
"text_col": "Cleo",
|
||||
"real_col": 3.14,
|
||||
"int_col": -255,
|
||||
"bool_col": True,
|
||||
"datetime_col": str(dt),
|
||||
}
|
||||
table1 = fresh_db["table1"]
|
||||
row_id = table1.insert(data).last_rowid
|
||||
# Duplicate table:
|
||||
table2 = table1.duplicate("table2")
|
||||
# Ensure data integrity:
|
||||
assert data == table2.get(row_id)
|
||||
# Ensure schema integrity:
|
||||
assert [
|
||||
{"name": "text_col", "type": "TEXT"},
|
||||
{"name": "real_col", "type": "REAL"},
|
||||
{"name": "int_col", "type": "INT"},
|
||||
{"name": "bool_col", "type": "INT"},
|
||||
{"name": "datetime_col", "type": "TEXT"},
|
||||
] == [{"name": col.name, "type": col.type} for col in table2.columns]
|
||||
Loading…
Add table
Add a link
Reference in a new issue