Skip to content

Commit adcf0b4

Browse files
authored
Improve get_subnet_with_ips performance (#33)
Use an ad-hoc SQL query to speed up subnet retrieval.
1 parent 5aad678 commit adcf0b4

File tree

2 files changed

+14
-14
lines changed

2 files changed

+14
-14
lines changed

ipam/client/backends/phpipam.py

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -497,26 +497,29 @@ def get_subnet_with_ips(self, subnet):
497497
Returns a subnet with all its allocated ip addresses
498498
"""
499499

500-
subnetid = self.find_subnet_id(subnet)
501-
502-
ipam_subnet = self.get_subnet_by_id(subnetid)
503-
504-
self.cur.execute('SELECT ip_addr,description,{},state '
505-
'FROM ipaddresses '
506-
'WHERE subnetId = {}'
507-
''.format(self.hostname_db_field, subnetid))
508-
500+
ipam_subnet = {}
501+
502+
self.cur.execute('SELECT ip.ip_addr,ip.description,ip.{},ip.state,'
503+
's.description,s.vlanId '
504+
'FROM ipaddresses ip LEFT JOIN subnets s '
505+
'ON ip.subnetId = s.id '
506+
"WHERE s.subnet='{}' AND s.mask='{}'"
507+
''.format(self.hostname_db_field,
508+
int(subnet.network_address),
509+
subnet.prefixlen))
509510
iplist = list()
510511
for row in self.cur:
512+
if not ipam_subnet:
513+
ipam_subnet['subnet'] = subnet
514+
ipam_subnet['description'] = row[4]
515+
ipam_subnet['vlan_id'] = row[5]
511516
item = {}
512517
item['ip'] = ip_address(int(row[0]))
513518
item['description'] = row[1]
514519
item['dnsname'] = row[2]
515520
item['state'] = row[3]
516521
iplist.append(item)
517-
518522
ipam_subnet['ips'] = iplist
519-
520523
return ipam_subnet
521524

522525
def get_ipnetwork_by_desc(self, description):

ipam/client/tests/test_phpipam.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -841,9 +841,6 @@ def test_get_subnet_with_ips(testphpipam):
841841
'dnsname': 'test-ip-14',
842842
'description': 'test ip #14'}]}
843843

844-
with pytest.raises(ValueError, match='Unable to get subnet id'):
845-
testphpipam.get_subnet_with_ips(ip_network('1.2.3.0/24'))
846-
847844

848845
def test_get_num_ips_by_desc(testphpipam):
849846
assert testphpipam.get_num_ips_by_desc('unknown ip') == 0

0 commit comments

Comments
 (0)