<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE table PUBLIC "-//kamailio.org//DTD DBSchema V1.1//EN" 
  "http://kamailio.org/pub/kamailio/dbschema/dtd/1.1/dbschema.dtd" [

<!ENTITY % entities SYSTEM "entities.xml">
%entities;

]>

<table>
  <name>uid_uri</name>
  <version>3</version>
  <type db="mysql">&MYSQL_TABLE_TYPE;</type>

  <column id="id">
    <name>id</name>
    <type>unsigned int</type>
    <size>&table_id_len;</size>
    <autoincrement/>
    <primary/>
    <type db="dbtext">int,auto</type>
    <description>Unique ID</description>
  </column>

  <column id="uri.uid">
	<name>uid</name>
	<name db="oracle">uuid</name>
	<type>string</type>
	<size>&id_len;</size>
  </column>

  <column id="uri.did">
	<name>did</name>
	<type>string</type>
	<size>&id_len;</size>
  </column>

  <column id="uri.username">
	<name>username</name>
	<type>string</type>
	<size>&user_len;</size>
  </column>

  <column id="uri.flags">
	<name>flags</name>
	<type>unsigned int</type>
	<default>0</default>
	<description>
	  Various flags (is_from, is_to, is_disabled, is_canon).
	</description>
  </column>

  <column id="uri.scheme">
    <name>scheme</name>
	<type>string</type>
	<size>8</size>
	<default>sip</default>
	<description>
	  URI scheme:
	  - SIP  
	  - SIPS 
	  - TEL  
	  - TELS 
	</description>
  </column>
  

  <index>
	<name>uri_idx1</name>
	<colref linkend="uri.username"/>
	<colref linkend="uri.did"/>
	<colref linkend="uri.scheme"/>
  </index>

  <index>
	<name>uri_uid</name>
	<colref linkend="uri.uid"/>
  </index>

  <verbatim db="mysql" id="func.touri">
	<create>
	  <![CDATA[
drop function if exists touri;
delimiter //
create function touri (puid varchar(64)) returns varchar(128) 
READS SQL DATA
begin
    declare tscheme varchar(8) default NULL;
	declare tuser varchar(64) default NULL;
	declare tdid varchar(64) default NULL;
	select scheme, username, did into tscheme, tuser, tdid 
        from uri where uid=puid and canonical(flags) limit 1;
	return concat(tscheme, ':', tuser, '@', todomain(tdid));
end
//
delimiter ;
]]>
	</create>
	<destroy>
	  drop function if exists touri;
	</destroy>
  </verbatim>

  <verbatim db="mysql" id="func.touid">
	<create>
	  <![CDATA[
drop function if exists touid;
delimiter //
create function touid (puri varchar(128)) returns varchar(128) 
READS SQL DATA
begin
    declare tscheme varchar(8) default "sip";
	declare tuid varchar(128) default NULL;
	declare i int default 0;
	declare tdid varchar(128) default NULL;
	set puri = lower(trim(puri));
	set i = locate(':', puri);
	if (i > 0) then
   	    set tscheme = left(puri, i - 1);
	    set puri = substr(puri FROM i + 1);
	end if;
	set i = locate('@', puri);
	if (i > 0) then
        set tdid = todid(substr(puri FROM i + 1));
	    set puri = left(puri, i - 1);
	end if;
	select uid into tuid from uid_uri where scheme=tscheme and
        username=puri and did=tdid and active(flags);
	return tuid;
end
//
delimiter ;
]]>
	</create>
	<destroy>
	</destroy>
  </verbatim>

</table>
