Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Easier inserts #703

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 15 additions & 4 deletions pypika/dialects.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@
Query,
QueryBuilder,
)
from pypika.terms import ArithmeticExpression, Criterion, EmptyCriterion, Field, Function, Star, Term, ValueWrapper
from pypika.terms import ArithmeticExpression, Criterion, EmptyCriterion, Field, Function, Star, Term, ValueWrapper, \
Values
from pypika.utils import QueryException, builder, format_quotes


Expand Down Expand Up @@ -119,6 +120,14 @@ def on_duplicate_key_update(self, field: Union[Field, str], value: Any) -> "MySQ
field = Field(field) if not isinstance(field, Field) else field
self._duplicate_updates.append((field, ValueWrapper(value)))

@builder
def on_duplicate_key_update_all(self) -> "MySQLQueryBuilder":
if self._ignore_duplicates:
raise QueryException("Can not have two conflict handlers")

for field in self._columns:
self._duplicate_updates.append((field, ValueWrapper(Values(field))))

@builder
def on_duplicate_key_ignore(self) -> "MySQLQueryBuilder":
if self._duplicate_updates:
Expand All @@ -133,7 +142,7 @@ def get_sql(self, **kwargs: Any) -> str:
if self._duplicate_updates:
querystring += self._on_duplicate_key_update_sql(**kwargs)
elif self._ignore_duplicates:
querystring += self._on_duplicate_key_ignore_sql()
querystring += self._on_duplicate_key_ignore_sql(**kwargs)
return querystring

def _for_update_sql(self, **kwargs) -> str:
Expand All @@ -158,8 +167,10 @@ def _on_duplicate_key_update_sql(self, **kwargs: Any) -> str:
)
)

def _on_duplicate_key_ignore_sql(self) -> str:
return " ON DUPLICATE KEY IGNORE"
def _on_duplicate_key_ignore_sql(self, **kwargs: Any) -> str:
# This feature isn't available in MySQL. This is a workaround where a field is set to itself on a duplicate key.
field_sql = self._columns[0].get_sql(**kwargs)
return f" ON DUPLICATE KEY UPDATE {field_sql}={field_sql}"

@builder
def modifier(self, value: str) -> "MySQLQueryBuilder":
Expand Down
13 changes: 13 additions & 0 deletions pypika/queries.py
Original file line number Diff line number Diff line change
Expand Up @@ -879,6 +879,19 @@ def insert(self, *terms: Any) -> "QueryBuilder":
self._apply_terms(*terms)
self._replace = False

@builder
def insert_dict(self, terms: dict) -> "QueryBuilder":
if self._insert_table is None:
raise AttributeError("'Query' object has no attribute '%s'" % "insert")

for term in terms:
if isinstance(term, str):
term = Field(term, table=self._insert_table)
self._columns.append(term)

self._apply_terms(*terms.values())
self._replace = False

@builder
def replace(self, *terms: Any) -> "QueryBuilder":
self._apply_terms(*terms)
Expand Down
2 changes: 2 additions & 0 deletions pypika/terms.py
Original file line number Diff line number Diff line change
Expand Up @@ -381,6 +381,8 @@ def get_formatted_value(cls, value: Any, **kwargs):
return str.lower(str(value))
if isinstance(value, uuid.UUID):
return cls.get_formatted_value(str(value), **kwargs)
if isinstance(value, bytes):
return "x'" + value.hex() + "'"
if value is None:
return "null"
return str(value)
Expand Down
37 changes: 37 additions & 0 deletions pypika/tests/test_inserts.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,15 @@ def test_insert_with_statement(self):
'WITH sub_qs AS (SELECT "id" FROM "abc") INSERT INTO "abc" SELECT "sub_qs"."id" FROM sub_qs', str(q)
)

def test_insert_dict(self):
d = {self.table_abc.foo: 1, self.table_abc.bar: "a", self.table_abc.buz: True}
query = (
Query.into(self.table_abc)
.insert_dict(d)
)

self.assertEqual('INSERT INTO "abc" ("foo","bar","buz") VALUES (1,\'a\',true)', str(query))


class PostgresInsertIntoOnConflictTests(unittest.TestCase):
table_abc = Table("abc")
Expand Down Expand Up @@ -740,6 +749,34 @@ def test_insert_ignore(self):
str(query),
)

def test_on_duplicate_key_update_all(self):
query = (
MySQLQuery.into(self.table_abc)
.columns(self.table_abc.foo, self.table_abc.bar, self.table_abc.baz)
.insert(1, "a", True)
.on_duplicate_key_update_all()
)

self.assertEqual(
"INSERT INTO `abc` (`foo`,`bar`,`baz`) VALUES (1,'a',true) ON DUPLICATE KEY "
"UPDATE `foo`=VALUES(`foo`),`bar`=VALUES(`bar`),`baz`=VALUES(`baz`)",
str(query),
)

def test_on_duplicate_key_ignore(self):
query = (
MySQLQuery.into(self.table_abc)
.columns(self.table_abc.foo, self.table_abc.bar, self.table_abc.baz)
.insert(1, "a", True)
.on_duplicate_key_ignore()
)

self.assertEqual(
"INSERT INTO `abc` (`foo`,`bar`,`baz`) VALUES (1,'a',true) ON DUPLICATE KEY "
"UPDATE `foo`=`foo`",
str(query),
)


class InsertSelectFromTests(unittest.TestCase):
table_abc, table_efg, table_hij = Tables("abc", "efg", "hij")
Expand Down