DBD::LDAP(3pm)
β¨ DBD::LDAP(3pm) β¨
okay bestie, sit down, hydrate, because this is the manual page for DBD::LDAP β straight out of the User Contributed Perl Documentation collection, and it is long. It's the module that lets you talk to LDAP using SQL, which is genuinely iconic behavior. No cap. π§π
πΈ NAME πΈ
DBD::LDAP β it provides an SQL/Perl DBI interface to LDAP. That's it, that's the whole name section, short and slay. β¨
π AUTHOR π
This module is Copyright (C) 2000-2019 by
Jim Turner
Email: turnerjw784 .att. yahoo dot com
All rights reserved.
You may distribute this module under the same terms as Perl itself. π
π PREREQUISITES π
before you can even think about vibing with this module, you need these:
Convert::ANS1β (required byNet::LDAP)Net::LDAPDBI- an LDAP database to connect to. yes, an actual one. you can't just manifest it. π
π¦ SYNOPSIS π¦
here's the whole flow, bestie β connecting, preparing, fetching, and dipping out:
use DBI;
$dbh = DBI->connect("DBI:LDAP:ldapdb",'user','password') #USER LOGIN.
or die "Cannot connect as user: " . $DBI::errstr;
$dbh = DBI->connect("DBI:LDAP:ldapdb") #ANONYMOUS LOGIN (Read-only).
or die "Cannot connect as guest (readonly): " . $DBI::errstr;
$sth = $dbh->prepare("select * from people where (cn like 'Smith%')")
or die "Cannot prepare: " . $dbh->errstr();
$sth->execute() or die "Cannot execute: " . $sth->errstr();
while ((@results) = $sth->fetchrow_array)
{
print "--------------------------------------------------------\n";
++$cnt;
while (@results)
{
print "------>".join('|',split(/\0/, shift(@results)))."\n";
}
}
$sth->finish();
$dbh->disconnect();
π DESCRIPTION π
so. LDAP stands for the "Lightweight Directory Access Protocol". want the lore? see: http://www.ogre.com/ldap/docs.html
DBD::LDAP is a DBI extension module that adds an SQL database interface to standard LDAP databases, plugging right into Perl's database-independent database interface. You're gonna need access to an existing LDAP database, or you set up your own using an LDAP server, ie. "OpenLDAP", see (http://www.openldap.org).
The main advantage of DBD::LDAP? The ability to query LDAP databases via standard SQL queries in leu of cryptic LDAP "filters". LDAP is optimized for quick lookup of existing data, but DBD::LDAP does support entry inserts, updates, and deletes with commit/rollback via the standard SQL commands! yes really, all of it. π₯
LDAP databases are "heirarchical" in structure, whereas the other DBD-supported databases are "relational" β and there is no LDAP-equivalent to SQL "tables", so DBD::LDAP maps a "table" interface over the LDAP "tree" via a configuration file you must set up. Each "table" is mapped to a common "base DN".
okay so picture this: a typical LDAP database of employees, across different departments, inside a company. You might have a "company" named "Acme" and the root "dn" of "dc=Acme, dc=com" (Acme.com). Below the company level are divisions, ie. "Widgets" and "Blivets". Each division would have an entry with a "dn" of "ou=Widgets, dc=Acme, dc=com", "ou=Blivets, dc=Acme, dc=com", etc. Employees within each division could have a "dn" like "cn=John Doe, ou=Widgets, dc=Acme, dc=com", etc.
With DBD::LDAP, we could create tables to access these different levels, ie. "top", which would have a "DN" of "dc=Acme, dc=com", "WidgetDivision" for "ou=Widgets, dc=Acme, dc=com". "BlivetDivision" for "ou=Blivets, dc=Acme, dc=com", etc. Tables can also be constained by additional attribute specifications (filters), ie constraining by "objectclass", ie. "(objectclass=person)". Then, doing a "select * from WidgetDivision" would display all "person"s with a "dn" containing "ou=Widgets, dc=Acme, dc=com". obsessed. π
π INSTALLATION π
Installing this module (and the prerequisites from above) is quite simple, fr fr. You just fetch the archive, extract it with
gzip -cd DBD-LDAP-####.tar.gz | tar xf -
-or-
tar -xzvf DBD-LDAP-####.tar.gz
(this is for Unix users, Windows users would prefer WinZip or something similar) and then enter the following:
cd DBD-LDAP-#.###
perl Makefile.PL
make
make test
If any tests fail, let me know. Otherwise go on with
make install
note that you almost definitely need root or administrator permissions. If you don't have them, read the ExtUtils::MakeMaker man page for details on installing in your own directories. π
π GETTING STARTED: π
- Create a "database", ie.
"foo"by creating a text file"foo.ldb". The general format of this file is:
----------------------------------------------------------
hostname[;port][:[root-dn][:[loginrule]]]
tablename1:[basedn]:[basefilter]:dnattrs:[visableattrs]:[insertattrs]: \\
[ldap_options]
tablename2:[basedn]:[basefilter]:dnattrs:[visableattrs]:[insertattrs]: \\
[ldap_options]
...
----------------------------------------------------------
here's what every lil field means, bestie:
<hostname>β represents the ldap server host name.<port>β represents the server's port, default is389.<root-dn>β if specified, is appended to the end of each tablename's base-dn.<loginrule>β if specified, converts single word "usernames" to the appropriate DN, ie:
"cn=*,<ROOT>" would convert user name "foo" to "cn=foo, " and append the "<root-dn>" onto that. The asterisk is converted to the user-name specified in the "connect" method. If not specified, the username specified in the "connect" method must be a full DN. If the "<root-dn>" is not specified, then the "<loginrule>" would need to be a full DN.
tablenameβ represents the name to be used in SQL statements for a given set of entries which make up a virtual "table".basednβ if specified, is appended to the"<root-dn>"to make up the common base DN for all entries in this table. If"<root-dn>"is not specified, then a full DN must be specified; otherwise, the default is the root-dn.basefilterβ if specified, specifies a filter to be used if no"where"-clause is specified in SQL queries. If a"where"-clause is specified, the resulting filter is"and"-ed with this one. The default is"(objectclass=*)".dnattrsβ specifies which attributes that values for which are to be appended to the left of the basedn to create DNs for new entries being inserted into the table.visableattrsβ if specified, one or more attributes separated by commas which will be sought when the SQL statement does not specify attributes, ie."select * from tablename". If not specified, the attributes of the first matching entry are returned and used for all entries matching a given query.insertattrsβ if specified, one or more attribute/value combinations to be added to any new entry inserted into the table, usually needed for objectclass values. The attributes and values usually correspond to those specivied in the"<basefilter>". The general format is:attr1=value1[|value2...],attr2=value1...,...These attributes and values will be joined with any user-specified values for these attributes.ldap_optionsβ if specified, can be any one or more of the following:ldap_sizelimitβ Limit the number of entries fetch by a query to this number (0 = no limit) - default: 0.ldap_timelimitβ Limit the search to this number of seconds per query. (0 = no limit) - default: 0.ldap_scopeβ specify the"scope"of the search. Values are:"base","one", and"sub", seeNet::LDAPdocs. Default is"one", meaning the set of records one level below the basedn."base"means search only the basedn, and"sub"means the union of entries at the"base"level and"one"level below.ldap_inseparatorβ specify the separator character/string to be used in queries to separate multiple values being specified for a given attribute. Default is"|".ldap_outseparatorβ specify the separator character/string to be used in queryies to separate multiple values displayed as a result of a query. Default is"|".ldap_firstonlyβ only display the 1st value fetched for each attribute per entry. This makes"ldap_outseparator"unnecessary.
- write your script to use DBI, ie:
#!/usr/bin/perl
use DBI;
$dbh = DBI->connect('DBD:LDAP:foo','me','mypassword') ||
die "Could not connect (".$DBI->err.':'.$DBI->errstr.")!";
...
- get your application working. π«Ά
πΎ INSERTING, FETCHING AND MODIFYING DATA πΎ
okay bestie, let's get our hands dirty fr. EXAMPLE: first we're gonna create a database called ldapdb with the tables we already talked about back in the DESCRIPTION section. In this little scenario, ldapserver is our LDAP server hostname[:port] or ip-address[:port]. If you ghost the port, it just defaults to 389, no drama. And dc=Acme, dc=com is our optional (relative) "root DN" for our "database". Then cn=*, <ROOT> is our optional "login rule", which lets our $dbh->connect() call just say a lil simple user-name instead of typing out a whole entire DN to log in. So in this example, if the "user-name" is Bob, it gets converted to cn=Bob, dc=Acme, dc=com by swapping <ROOT> for the "root DN" and swapping any asterisk for the "user-name". And if the user-name is a single-pair RDN (relative DN)? Then the root DN just gets appended onto it, ie. cn=Bob => cn=Bob, dc=Acme, dc=com. If the user-name is empty, blank, or already a full DN, then literally no transformation happens at all (see the example below, bestie):
EXAMPLE database file with 3 tables defined (and yes, you the user have to create one for each of your own databases). NOTE: the "root dn" here is the root access level for the database and tables being created, NOT necessarily the "root dn" for the entire LDAP tree itself β because the user (that's you, developer π ) may not want to permit access in a given "database" above a certain level in the LDAP tree:
----------------- file "ldapdb.ldb" ----------------
ldapserver:dc=Acme, dc=com:cn=*,<ROOT>
top:::dc
WidgetDivision:ou=Widgets, :&(objectclass=top)(objectclass=person): \
cn:cn,sn,ou,title,telephonenumber,description,objectclass,dn: \
objectclass=top|person|organizationalPerson:ldap_outseparator => ":"
BlivetDivision:ou=Blivets, :&(objectclass=top)(objectclass=person): \
cn:cn,sn,ou,title,telephonenumber,description,objectclass,dn: \
objectclass=top|person|organizationalPerson:ldap_outseparator => ":"
----------------------------------------------------
Now, to connect to the freshly created example database above, you'd do:
my $dbh = DBI->connect('DBD:LDAP:ldapdb','Bob','Bobs_password') ||
die "Could not connect (".$DBI->err.':'.$DBI->errstr.")!";
In this case Bob would be converted to cn=Bob, dc=Acme, dc=com. It could've also been specified as cn=Bob or the full cn=Bob, dc=Acme, dc=com, based on that first line of the database (.ldb) file we created above. A different full DN could also have been specified, sky's the limit β¨. NOTE: if your login user-names aren't defined in your database's common root-dn, it may be necessary to specify a relative DN to log in, ie. cn=Bob, ou=Widgets or a full DN. And if you need or wish to mandate a full DN to log in and connect? Simply omit the login-rule (that's the 3rd argument of line 1 in your database file) which in this case is the cn=*,<ROOT> part. bye π
The following examples insert some data in a table and fetch it back. First, all the data in the string:
$dbh->do(q{
INSERT INTO top (ou, cn, objectclass)
VALUES ('Widgets', 'WidgetDivision', 'top|organizationalUnit')
};
Next, an example using parameters:
$dbh->do("INSERT INTO WidgetDivision (cn,sn,title,telephonenumber) VALUES (?, ?, ?, ?)",
'John Doe','DoeJ','Manager','123-1111');
$dbh->commit;
NOTE: Unlike most other DBD modules which support transactions, changes made do NOT show up until thecommitfunction is called, unlessAutoCommitis set. This is because fetches are done from the LDAP server and changes don't take effect there until the Net::LDAPupdatefunction is called, which is whatcommitcalls. so like, don't be confused when nothing appears, bestie π
NOTE: Thednfield is generated automatically from the basednand the dn component fields specified bydnattrs. If you try to insert a value directly into it, it will be ignored. Also, if not specified, any attribute/value combinations specified in theinsertattrsoption will be added automatically. the more you know π
To retrieve data, you can use the following:
my($query) = "SELECT * FROM WidgetDivision WHERE cn like 'John%' ORDER BY cn";
my($sth) = $dbh->prepare($query);
$sth->execute();
while (my $entry = $sth->fetchrow_hashref) {
print("Found result record: cn = ", $entry->{'cn'},
", phone = ", $row->{'telephonenumber'});
}
$sth->finish();
The SQL SELECT statement above (combined with the table information in the ldapdb.ldb database file) would generate and execute the following equivalent LDAP Search:
base => 'ou=Widgets, dc=Acme, dc=com',
filter => '(&(&(objectclass=top)(objectclass=person))(cn=John*))',
scope => 'one',
attrs => 'cn,sn,ou,title,telephonenumber,description,objectclass,dn'
See the DBI manpage for details on these methods. See the Data rows are modified with the UPDATE statement:
$dbh->do("UPDATE WidgetDivision SET description = 'Outstanding Employee' WHERE cn = 'John Doe'");
NOTE: You can NOT change thednfield directly β direct changes will be ignored. You change therdncomponent of thednfield by changing the value of the other field(s) which are appended to the basedn. Also, if not specified, any attribute/value combinations specified in theinsertattrsoption will be added automatically. okay so that's the whole vibe, don't fight it π
Likewise you use the DELETE statement for removing entries:
$dbh->do("DELETE FROM WidgetDivision WHERE description = 'Outstanding Employee'");
π METADATA π
The following attributes are handled by DBI itself and not by DBD::LDAP, so they should all work as expected, no cap:
PrintError
RaiseError
Warn
The following DBI attributes are handled by DBD::LDAP:
AutoCommitβ Works. slay πNUM_OF_FIELDSβ Valid after$sth->executeNUM_OF_PARAMSβ Valid after$sth->prepareNAMEβ Valid after$sth->execute; undef for Non-Select statements.NULLABLEβ Not really working. Always returns an array ref of one's, as DBD::LDAP always allows NULL (handled as an empty string). Valid after$sth->execute.LongReadLenβ Should workLongTruncOkβ Should work
These attributes and methods are not supported, rip πͺ¦:
bind_param_inout
CursorName
In addition to the DBI attributes, you can use the following dbh attributes. These attributes are read-only after connect. yes, read-only, don't try it π«
ldap_dbuserβ Current database user.ldap_HOMEβ Environment variable specifying a path to search for LDAP databases (*.ldb) files.
π§ DRIVER PRIVATE METHODS π§
DBI->data_sources()β Thedata_sourcesmethod returns a list of "databases" (.ldbfiles) found in the current directory and, if specified, the path in theldap_HOMEenvironment variable. it's giving detective energy π$dbh->tables()β This method returns a list of table names specified in the current database. Example:
my($dbh) = DBI->connect("DBI:LDAP:mydatabase",'me','mypswd');
my(@list) = $dbh->func('tables');
π§° OTHER SUPPORTING UTILITIES π§°
(this section is literally empty, bestie β nothing to see here, it's giving minimalism β¨)
π§ RESTRICTIONS π§
DBD::LDAP currently treats all data as strings and all fields as VARCHAR(255) (type 12), though data is not limited nor truncated to that arbitrary length β it's just returned as that by DBI's *info() functions. so the number is a lie but also not a lie, iykyk π
Currently, you must define tables manually in the <database>.ldb file using your favorite text editor. yes, by hand. old school. π
ποΈ TODO ποΈ
Create Table,Alter Table, andDrop TableSQL functions for creating, altering, and deleting the tables defined in the<database>.ldbfile.- Some kind of datatype support, ie. numeric (for sorting), CHAR for padding, Long/Blob - for >255 chars per field, etc.
manifesting these fr fr πβ¨
π KNOWN BUGS π
none - (yet).
not the "yet" π that's so ominous bestie
π SEE ALSO π
- Net::LDAP
- DBI
and that's the whole page, bestie!! this iconic lil manual is perl v5.40.1, dated 2025-09-14, and it's page DBD::LDAP(3pm) of your very own system docs. go forth and LDAP responsibly π«Άπβ¨
π¦ where this page comes from
- ubuntu resolute: libdbd-ldap-perl 1.00-1 Β· Artistic-1.0-Perl OR GPL-1.0-only
- ubuntu stonking: libdbd-ldap-perl 1.00-1 Β· Artistic-1.0-Perl OR GPL-1.0-only
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms