You are on page 1of 720

Replication and

Synchronization Guide

Last modified: March 2000


Part Number: MC0061
Copyright © 2000 Sybase, Inc. All rights reserved.
No part of this publication may be reproduced, transmitted, or translated in any form or by any means, electronic,
mechanical, manual, optical, or otherwise, without the prior written permission of Sybase, Inc.
Sybase, SYBASE (logo), ADA Workbench, Adaptable Windowing Environment, Adaptive Component Architecture,
Adaptive Server, Adaptive Server Anywhere, Adaptive Server Enterprise, Adaptive Server Enterprise Monitor, Adaptive
Server Enterprise Replication, Adaptive Server Everywhere, Adaptive Server IQ, Adaptive Warehouse, AnswerBase,
Anywhere Studio, Application Manager, AppModeler, APT-Build, APT-Edit, APT-Execute, APT-FORMS, APT-Library,
APT-Translator, APT Workbench, ASEP, Backup Server, BayCam, Bit-Wise, Certified PowerBuilder Developer, Certified
SYBASE Professional, Certified SYBASE Professional (logo), ClearConnect, Client Services, Client-Library, CodeBank,
Cohesion, Column Design, ComponentPack, Connection Manager, CSP, Data Pipeline, Data Workbench, DataArchitect,
Database Analyzer, DataExpress, DataServer, DataWindow, DB-Library, dbQueue, Developers Workbench, Direct
Connect Anywhere, DirectConnect, Distribution Director, Dynamo, E-Anywhere, E-Whatever, Electronic Case
Management, Embedded SQL, EMS, Enterprise Application Server, Enterprise Application Studio, Enterprise
Client/Server, Enterprise Connect, Enterprise Data Studio, Enterprise Manager, Enterprise SQL Server Manager, Enterprise
Work Architecture, Enterprise Work Designer, Enterprise Work Modeler, EWA, Financial Fusion, First Impression,
Formula One, Gateway Manager, GeoPoint, ImpactNow, InfoMaker, Information Anywhere, Information Everywhere,
InformationConnect, InstaHelp, Intellidex, InternetBuilder, iScript, Jaguar CTS, jConnect for JDBC, KnowledgeBase,
Logical Memory Manager, MainframeConnect, Maintenance Express, MAP, MDI Access Server, MDI Database Gateway,
media.splash, MetaWorks, MethodSet, MobiCATS, MySupport, Net-Gateway, Net-Library, NetImpact, Next Generation
Learning, Next Generation Learning Studio, O DEVICE, OASiS, OASiS (logo), ObjectConnect, ObjectCycle,
OmniConnect, OmniSQL Access Module, OmniSQL Toolkit, Open Client, Open Client/Server, Open Client/Server
Interfaces, Open ClientConnect, Open Gateway, Open Server, Open ServerConnect, Open Solutions, Optima++,
Partnerships that Work, PB-Gen, PC APT Execute, PC DB-Net, PC Net Library, PhysicalArchitect, Power Through
Knowledge, Power++, power.stop, PowerAMC, PowerBuilder, PowerBuilder Foundation Class Library, PowerDesigner,
PowerDimensions, PowerDynamo, PowerJ, PowerScript, PowerSite, PowerSocket, Powersoft, Powersoft Portfolio,
Powersoft Professional, PowerStage, PowerStudio, PowerTips, PowerWare Desktop, PowerWare Enterprise,
ProcessAnalyst, Relational Beans, Replication Agent, Replication Driver, Replication Server, Replication Server Manager,
Replication Toolkit, Report Workbench, Report-Execute, Resource Manager, RW-DisplayLib, RW-Library, S-Designor,
S Designor, SAFE, SAFE/PRO, SDF, Secure SQL Server, Secure SQL Toolset, Security Guardian, SKILS, smart.partners,
smart.parts, smart.script, SQL Advantage, SQL Anywhere, SQL Anywhere Studio, SQL Code Checker, SQL Debug,
SQL Edit, SQL Edit/TPU, SQL Everywhere, SQL Modeler, SQL Remote, SQL Server, SQL Server Manager, SQL Server
SNMP SubAgent, SQL Server/CFT, SQL Server/DBM, SQL SMART, SQL Station, SQL Toolset, SQLJ, Startup.Com,
STEP, SupportNow, Sybase Central, Sybase Client/Server Interfaces, Sybase Development Framework, Sybase Financial
Server, Sybase Gateways, Sybase Learning Connection, Sybase SQL Desktop, Sybase SQL Lifecycle, Sybase SQL
Workgroup, Sybase Synergy Program, Sybase User Workbench, Sybase Virtual Server Architecture, Sybase MPP,
SybaseWare, Syber Financial, SyberAssist, SyBooks, System XI (logo), System 10, System 11, SystemTools, Tabular Data
Stream, The Enterprise Client/Server Company, The Extensible Software Platform, The Future Is Wide Open,
The Learning Connection, The Model For Client/Server Solutions, The Online Information Center, Transact-SQL,
Translation Toolkit, Turning Imagination Into Reality, UltraLite, UNIBOM, Unilib, Uninull, Unisep, Unistring,
URK Runtime Kit for UniCode, Viewer, Visual Components, VisualSpeller, VisualWriter, VQL, Warehouse Control
Center, Warehouse Studio, Warehouse WORKS, WarehouseArchitect, Watcom, Watcom SQL Server, Watcom SQL,
Web.PB, Web.SQL, Web Deployment Kit, WebSights, WebViewer, WorkGroup SQL Server, XA-Library, XA-Server,
and XP Server are trademarks of Sybase, Inc. or its subsidiaries.
Certicom, MobileTrust, and SSL Plus are trademarks and Security Builder is a registered trademark of Certicom Corp.
Copyright © 1997–2000 Certicom Corp. Portions are Copyright © 1997–1998, Consensus Development Corporation, a
wholly owned subsidiary of Certicom Corp. All rights reserved. Contains an implementation of NR signatures, licensed
under U.S. patent 5,600,725. Protected by U.S. patents 5,787,028; 4,745,568; 5,761,305. Patents pending.
All other trademarks are property of their respective owners.
Last modified: March 2000. Part Number: MC0061.
Contents

About this Manual............................................................. xi


Documentation conventions.....................................................xii

PART ONE
Replication Basics............................................................. 1

1 Sybase Replication Technologies .................................... 3


Introduction ............................................................................... 4
Consolidated and remote databases ........................................ 5
Propagation methods ................................................................ 8
Sybase replication technologies ............................................. 11

PART TWO
MobiLink Synchronization .............................................. 17

2 Introducing MobiLink Synchronization .......................... 19


Overview ................................................................................. 20
What’s new in 7.0.................................................................... 23
What’s new in 6.0.3................................................................. 25

3 Synchronization Basics .................................................. 27


Parts of the synchronization system ....................................... 28
The MobiLink synchronization server ..................................... 29
MobiLink clients....................................................................... 30
The synchronization process .................................................. 32
The consolidated database..................................................... 35
Creating a consolidated database .......................................... 38
Running the MobiLink synchronization server ........................ 40
Details of the synchronization process ................................... 43
Character-set considerations .................................................. 48
Transport-layer security .......................................................... 51

iii
4 Writing Synchronization Scripts .................................... 57
Introduction to synchronization scripts.................................... 58
Scripts and the synchronization process ................................ 62
Script versions ........................................................................ 67
Adding scripts to your consolidated database ........................ 68
Writing scripts to download rows ............................................ 72
Writing scripts to upload rows ................................................. 77
Writing scripts to handle errors ............................................... 81
DBMS-dependent scripts ........................................................ 84

5 Synchronization Techniques .......................................... 85


Introduction ............................................................................. 86
Development tips .................................................................... 88
The CustDB sample code ....................................................... 89
Synchronization performance tips .......................................... 93
Snapshot synchronization....................................................... 94
Timestamp-based synchronization ......................................... 96
Partitioning rows among remote databases ......................... 101
Maintaining unique primary keys with primary-key
pools...................................................................................... 105
Handling conflicts.................................................................. 109
Miscellaneous techniques..................................................... 113
Schema changes in remote databases ................................ 115

6 Adaptive Server Anywhere Synchronization using


MobiLink – A Tutorial .................................................... 117
Introduction ........................................................................... 118
Creating a SQL file for the consolidated database ............... 119
Running the synchronization tutorial..................................... 122
Summary............................................................................... 130

7 Adaptive Server Anywhere Clients............................... 131


Introduction ........................................................................... 132
Synchronization definitions ................................................... 134
Writing synchronization definitions ....................................... 136
Initiating synchronization....................................................... 138
Deployment management..................................................... 141
The reference database........................................................ 142
Extracting the remote databases .......................................... 144
Partitioning data between remote sites................................. 146
Temporarily stopping synchronization of deletes.................. 147

iv
8 Reference ....................................................................... 149
Utility programs ..................................................................... 150
MobiLink system tables......................................................... 167
Data-type conversions .......................................................... 168
Scripts ................................................................................... 173
Stored procedures................................................................. 190
SQL statements .................................................................... 192

PART THREE
SQL Remote ................................................................... 211

9 Welcome to SQL Remote .............................................. 213


About SQL Remote ............................................................... 214
About this manual ................................................................. 215
New features in version 7.0 .................................................. 217
New features in version 6.0.3 ............................................... 218
New features in version 6.0.2 ............................................... 220

10 SQL Remote Concepts .................................................. 221


SQL Remote components..................................................... 222
Publications and subscriptions.............................................. 225
SQL Remote features ........................................................... 227
Some sample installations .................................................... 229

11 Setting Up SQL Remote ................................................ 233


Setup overview...................................................................... 234
Preparing your Adaptive Server Enterprise server ............... 235
Upgrading SQL Remote for Adaptive Server
Enterprise.............................................................................. 239
Uninstalling SQL Remote...................................................... 240

12 A Tutorial for Adaptive Server Anywhere Users.......... 241


Tutorial overview ................................................................... 242
A tutorial using Sybase Central............................................. 245
Setting up a consolidated database...................................... 248
Set up the remote database in Sybase Central .................... 253
A tutorial using Interactive SQL and DBXTRACT................. 255
Set up the consolidated database......................................... 257
Set up the remote database.................................................. 261
Start replicating data ............................................................. 263
A sample publication ............................................................. 267

v
13 A Tutorial for Adaptive Server Enterprise Users......... 269
Introduction ........................................................................... 270
Setting up SQL Remote using Sybase Central..................... 273
Setting up the consolidated database................................... 276
Set up the remote database in Sybase Central .................... 281
A tutorial using isql and ssxtract ........................................... 283
Setting up the consolidated database................................... 286
Start replicating data ............................................................. 292

14 Principles of SQL Remote Design ................................ 297


Design overview.................................................................... 298
How statements are replicated ............................................. 302
How data types are replicated .............................................. 307
Who gets what? .................................................................... 310
Replication errors and conflicts............................................. 312

15 SQL Remote Design for Adaptive Server Anywhere... 315


Design overview.................................................................... 316
Creating publications ............................................................ 317
Publication design for Adaptive Server Anywhere................ 327
Partitioning tables that do not contain the
subscription expression ........................................................ 330
Sharing rows among several subscriptions .......................... 338
Managing conflicts ................................................................ 347
Ensuring unique primary keys............................................... 357
Creating subscriptions .......................................................... 366

16 SQL Remote Design for Adaptive Server Enterprise .. 369


Design overview.................................................................... 370
Creating publications ............................................................ 371
Publication design for Adaptive Server Enterprise ............... 376
Partitioning tables that do not contain the
subscription column .............................................................. 378
Sharing rows among several subscriptions .......................... 386
Managing conflicts ................................................................ 394
Ensuring unique primary keys............................................... 405
Creating subscriptions .......................................................... 411

17 Deploying and Synchronizing Databases.................... 413


Deployment overview............................................................ 414
Test before deployment ........................................................ 415

vi
Synchronizing databases...................................................... 417
Using the extraction utility ..................................................... 419
Synchronizing data over a message system ........................ 427

18 SQL Remote Administration ......................................... 429


Management overview.......................................................... 430
Managing SQL Remote permissions .................................... 431
Using message types............................................................ 441
Running the Message Agent................................................. 454
Tuning Message Agent performance.................................... 458
Encoding and compressing messages ................................. 465
The message tracking system .............................................. 467

19 Administering SQL Remote for Adaptive Server Anywhere


........................................................................................ 471
Running the Message Agent................................................. 472
Error reporting and handling ................................................. 474
Transaction log and backup management............................ 478
Using passthrough mode ...................................................... 489

20 Administering SQL Remote for Adaptive Server Enterprise


........................................................................................ 493
How the Message Agent for Adaptive Server
Enterprise works ................................................................... 494
Running the Message Agent................................................. 499
Error reporting and handling ................................................. 501
Adaptive Server Enterprise transaction log and
backup management ............................................................ 503
Making schema changes ...................................................... 506
Using passthrough mode ...................................................... 507

21 Using SQL Remote with Replication Server ................ 509


When you need to use the SQL Remote Open
Server.................................................................................... 510
Architecture for Replication Server/SQL Remote
installations ........................................................................... 511
Setting up SQL Remote Open Server................................... 514
Configuring Replication Server ............................................. 517
Other issues .......................................................................... 519

vii
22 Utilities and Options Reference.................................... 521
The Message Agent.............................................................. 522
The Database Extraction utility ............................................. 531
The SQL Remote Open Server............................................. 539
SQL Remote options............................................................. 542

23 System Objects for Adaptive Server Anywhere .......... 547


SQL Remote system tables .................................................. 548
SQL Remote system views................................................... 554

24 System Objects for Adaptive Server Enterprise.......... 557


SQL Remote system tables .................................................. 558
SQL Remote system views................................................... 566
Stable Queue tables ............................................................. 570

25 Command Reference for Adaptive Server Anywhere . 575


ALTER PUBLICATION statement ........................................ 577
ALTER REMOTE MESSAGE TYPE statement.................... 578
CREATE PUBLICATION statement ..................................... 579
CREATE REMOTE MESSAGE TYPE statement................. 581
CREATE SUBSCRIPTION statement .................................. 583
CREATE TRIGGER statement ............................................. 584
DROP PUBLICATION statement.......................................... 587
DROP REMOTE MESSAGE TYPE statement ..................... 588
DROP SUBSCRIPTION statement....................................... 589
GRANT CONSOLIDATE statement...................................... 590
GRANT PUBLISH statement ................................................ 592
GRANT REMOTE statement ................................................ 593
GRANT REMOTE DBA statement........................................ 595
PASSTHROUGH statement ................................................. 596
REMOTE RESET statement................................................. 597
REVOKE CONSOLIDATE statement ................................... 598
REVOKE PUBLISH statement.............................................. 599
REVOKE REMOTE statement.............................................. 600
REVOKE REMOTE DBA statement ..................................... 601
SET REMOTE OPTION statement....................................... 602
START SUBSCRIPTION statement ..................................... 604
STOP SUBSCRIPTION statement ....................................... 606
SYNCHRONIZE SUBSCRIPTION statement....................... 607
UPDATE statement............................................................... 608

viii
26 Command Reference for Adaptive Server Enterprise . 611
sp_add_article procedure ..................................................... 613
sp_add_article_col procedure............................................... 615
sp_add_remote_table procedure .......................................... 616
sp_create_publication procedure.......................................... 618
sp_drop_publication procedure............................................. 619
sp_drop_remote_type procedure.......................................... 620
sp_drop_sql_remote procedure ............................................ 621
sp_grant_consolidate procedure........................................... 622
sp_grant_remote procedure.................................................. 624
sp_link_option procedure...................................................... 626
sp_modify_article procedure................................................. 628
sp_modify_remote_table procedure ..................................... 630
sp_passthrough procedure ................................................... 632
sp_passthrough_piece procedure......................................... 633
sp_passthrough_stop procedure .......................................... 635
sp_passthrough_subscription procedure.............................. 636
sp_passthrough_user procedure .......................................... 637
sp_populate_sql_anywhere procedure ................................. 638
sp_publisher procedure ........................................................ 639
sp_queue_clean procedure .................................................. 640
sp_queue_confirmed_delete_old procedure ........................ 641
sp_queue_confirmed_transaction procedure ....................... 642
sp_queue_delete_old procedure .......................................... 643
sp_queue_drop procedure.................................................... 644
sp_queue_dump_database procedure ................................. 645
sp_queue_dump_transaction procedure .............................. 646
sp_queue_get_state procedure ............................................ 647
sp_queue_log_transfer_reset procedure.............................. 648
sp_queue_read procedure.................................................... 649
sp_queue_reset procedure ................................................... 650
sp_queue_set_confirm procedure ........................................ 651
sp_queue_set_progress procedure ...................................... 652
sp_queue_transaction procedure ......................................... 653
sp_remote procedure ............................................................ 654
sp_remote_option procedure ................................................ 655
sp_remote_type procedure ................................................... 656
sp_remove_article procedure ............................................... 657
sp_remove_article_col procedure......................................... 658
sp_remove_remote_table procedure .................................... 659
sp_revoke_consolidate procedure ........................................ 660
sp_revoke_remote procedure ............................................... 661
sp_subscription procedure.................................................... 662
sp_subscription_reset procedure.......................................... 663

ix
PART FOUR
Appendix ........................................................................ 665

A Enterprise and Anywhere: Differences ........................ 667


Types of difference ............................................................... 668
Differences in functionality .................................................... 669
Differences in approach ........................................................ 670
Limitations for Enterprise to Enterprise replication ............... 672

B Supported Platforms and Message Links.................... 675


Supported message systems ............................................... 676
Supported operating systems ............................................... 677

Index............................................................................... 679

x
About this Manual

Subject
This manual describes MobiLink, a session-based synchronization system,
and SQL Remote, a message-based replication system. Both Sybase
technologies allow two-way replication. Either can be used in mobile
computing environments.

Audience
This manual is for users of Adaptive Server Anywhere and Adaptive Server
Enterprise who wish to add synchronization or replication to their
information systems.
Contents
Topic Page
Documentation conventions xii

xi
Documentation conventions
This section lists the typographic and graphical conventions used in this
documentation.

Syntax conventions
The following conventions are used in the SQL syntax descriptions:
♦ Keywords All SQL keywords are shown in UPPER CASE. However,
SQL keywords are case insensitive, so you can enter keywords in any
case you wish; SELECT is the same as Select which is the same as
select.
♦ Placeholders Items that must be replaced with appropriate identifiers
or expressions are shown in italics.
♦ Continuation Lines beginning with ... are a continuation of the
statements from the previous line.
♦ Repeating items Lists of repeating items are shown with an element
of the list followed by an ellipsis (three dots). One or more list elements
are allowed. If more than one is specified, they must be separated by
commas.
♦ Optional portions Optional portions of a statement are enclosed by
square brackets. For example, …
RELEASE SAVEPOINT [ savepoint-name ]
… indicates that the savepoint-name is optional. The square brackets
should not be typed.
♦ Options When none or only one of a list of items must be chosen, the
items are separated by vertical bars and the list enclosed in square
brackets.
For example, …
[ ASC | DESC ]
… indicates that you can choose one of ASC, DESC, or neither. The
square brackets should not be typed.
♦ Alternatives When precisely one of the options must be chosen, the
alternatives are enclosed in curly braces. For example …
QUOTES { ON | OFF }
… indicates that exactly one of ON or OFF must be provided. The
braces should not be typed.

xii
Graphic icons
The following icons are used in this documentation:

Icon Meaning

A client application.

A database server, such as Sybase Adaptive Server


Anywhere or Adaptive Server Enterprise.

An UltraLite application and database server.


In UltraLite, the database server and the application
are part of the same process.

A database.
In some high-level diagrams, the icon may be used to
represent both the database and the database server
that manages it.

Replication or synchronization middleware.


These pieces of software assist in sharing data among
databases. Examples are the MobiLink
synchronization server, the SQL Remote Message
Agent, and the Replication Agent (Log Transfer
Manager) for use with Replication Server.

Installed files
The following terms are used throughout the manual:
♦ Installation directory The directory into which you install
SQL Anywhere Studio.

xiii
♦ Executable directory The executables and other files for each
operating system are held in an executable subdirectory of the
installation directory. This subdirectory has the following name:
♦ Windows NT and Windows 95/98 win32
♦ UNIX bin
♦ NetWare and Windows CE The executables are held in the
SQL Anywhere installation directory itself on these platforms.

xiv
P A R T O N E

Replication Basics

This part describes general replication concepts and provides an overview of


the Sybase replication technologies, including MobiLink, SQL Remote, and
Replication Server. It provides guidelines for selecting the most appropriate
technology.

1
2
C H A P T E R 1

Sybase Replication Technologies

About this chapter Data replication is the sharing of data among physically distinct databases.
When an application modifies shared data at any one database, the changes
are propagated to the other databases in the replication setup. Changes can be
propagated by various means and through a variety of channels, preserving
data integrity yet allowing flexible replication setups.
Sybase has three replication technologies. MobiLink and SQL Remote are
designed for replication between a central database and a large number of
remote databases. Replication Server is intended for near-real-time
replication between a relatively small number of databases.
Contents
Topic Page
Introduction 4
Consolidated and remote databases 5
Propagation methods 8
Sybase replication technologies 11

3
Introduction

Introduction
This section introduces basic concepts in data replication.

Benefits of data replication


Data availability One of the key benefits of a data replication system is that data is made
available locally, rather than through potentially expensive, less reliable, and
slow connections to a single central database. Data is accessible locally even
in the absence of any connection to a central server, so that you are not cut
off from data in the event of a failure of a long-distance network connection.
Response time Replication improves response times for data requests for two reasons.
Retrieval rates are faster because requests are processed on a local server,
without accessing a wide area network. Also, local processing offloads work
from a central database server so that competition for processor time is
decreased.

Challenges for replication technologies


Any replication technology must address several challenges that arise as a
result of the increased flexibility permitted by replication.
Transactional One of the challenges of any replication system is to ensure that each
integrity database retains transactional integrity at all times.
Some replication systems, such as Sybase Replication Server and
SQL Remote, replicate portions of the transaction log in such a way that
transactions are replicated atomically: either a whole transaction is
replicated, or none of it is replicated. This ensures transactional integrity at
each database in the setup.
Other technologies, such as Sybase MobiLink, replicate data by
consolidating changes made in multiple, committed transactions. These
changes are applied to another database in a single transaction.
Data consistency Another challenge to replication systems is to maintain data consistency
throughout the setup. Replication systems maintain a loose consistency in
the setup as a whole: that is, all changes are replicated to each site over time
in a consistent manner, but different sites may have different copies of data
at any instant.

4
Chapter 1 Sybase Replication Technologies

Consolidated and remote databases

Both MobiLink and SQL Remote provide data replication between a


consolidated database and a set of remote databases.
A consolidated database is a database that contains all the data to be
replicated. A remote database is a database that may be running at the same
site as the consolidated database or at a physically distant site.
The figure shows a schematic illustration of a small installation.

Consolidated
database

Remote Remote Remote Remote


database database database database

Remote users A replication installation includes many remote databases. Each remote
database contains a subset of the information in the consolidated database.
Each remote database is a physically separate database, usually on a separate
computer. All remote databases must stay consistent with the consolidated
database.
The entire replication setup may be considered a single dispersed database,
with the master copy of all shared data being kept at the consolidated
database.
Each remote site that submits replications to the consolidated database is
considered to be a remote user of the consolidated database. In the case that
a remote site is a multi-user server, the entire site is considered to be a single
remote user of the consolidated database.

Hierarchical database configurations


For databases in a hierarchical configuration, every database has a single
parent database, except the consolidated database, which has no parent.

5
Consolidated and remote databases

SQL Remote supports hierarchical configurations of databases; it does not


support peer-to-peer replication or other non-hierarchical configurations.
MobiLink is also normally used with a hierarchical configuration, but can
also be used in other configurations.
For any two databases in a hierarchical configuration, one is always above or
below the other in the hierarchy.

Hierarchical
database
configurations

For databases in a non-hierarchical configuration, there is not any well-


defined notion of above or below.

Non-hierarchical configurations

In a MobiLink or SQL Remote installation, each database contains all or a


subset of the data replicated by the database above it in the hierarchy.
Remote databases can contain tables that are not present at the consolidated
database, as long as they are not involved in replication. SQL Remote
requires that the table and column names in the remote databases match the
ones in the consolidated database. In contrast, MobiLink allows data to be
stored in different columns and tables in the remote databases than in the
consolidated database, allowing greater flexibility.

6
Chapter 1 Sybase Replication Technologies

Two-way replication
All Sybase replication technologies provide two-way replication: changes
made at the consolidated database are propagated to remote databases and
changes made at remote databases are propagated to the consolidated
database and, hence, to other remote databases. Sybase Replication Server
requires that a particular piece of data can be modified at only one location.
Both SQL Remote and MobiLink allow the same data to be changed
simultaneously at multiple locations and provide a means of resolving any
conflicts.

7
Propagation methods

Propagation methods
When a transaction modifies shared data at any one database, the transaction
or changes must be replicated to the other databases in the replication setup.
There are various means by which this task may be accomplished.

Session-based replication: MobiLink

In a session-based replication scheme, synchronization occurs in real time


over some sort of direct communications link. For example, the connection
could be over a modem, network, or radio modem. Remote sites connect at
intervals of minutes, hours, days, or weeks.
A session-based synchronization process is analogous to a telephone
conversation in which all outstanding issues at both ends are resolved. The
process follows a particular format. A MobiLink remote site begins by
opening a connection to a MobiLink synchronization server and uploading a
complete list of all the changes made to the remote database since the
previous synchronization. Upon receiving this data, the server updates the
consolidated database, then sends back all relevant changes. The remote site
incorporates the entire set of changes, then sends back a confirmation and
closes the connection.

Message-based replication: SQL Remote

SQL Remote exchanges data between databases using messages. Messages


are typically files, placed in a particular directory, or specially formatted
e-mail messages. A message agent, attached to each database, sends
messages regarding changes to its own data. The same agent also receives
messages from one or more other databases and modifies the database,
according to the contents of the received messages. This system allows
replication between databases that have no direct connection: an occasional
message-based connection such as e-mail or a periodic dial-up link is
sufficient.
In message-based communications, each message carries its destination
address and other control information, so that no direct connection is needed
between applications exchanging information. For example, an e-mail
message contains the destination address; there is no direct connection
between the sending server and the recipient.

8
Chapter 1 Sybase Replication Technologies

Message services Just as session-based client/server applications rely on network


use store and communication protocol stacks, such as TCP/IP or Novell NetWare’s IPX, so
forward methods message-based applications rely on message services such as Internet Simple
Mail Transfer Protocol (SMTP), Microsoft’s Messaging API (MAPI), Lotus’
Vendor Independent Messaging (VIM), or a simple shared file link.
Message services use store-and-forward methods to get each message to its
destination: for example, e-mail systems store messages until the recipient
opens their mail folder to read their mail, at which time the e-mail system
forwards the message.
Building a replication system on top of a message system means that a
message-based replication system, such as SQL Remote, does not need to
implement a store-and-forward system to get messages to their destination.
Just as session-based client/server applications do not implement their own
protocol stacks to pass information between client and server, so
SQL Remote uses existing message systems to pass the messages.

Message system
transport

Message
system

Message Message
System System
Client Client

Guaranteed To work reliably, a message-based system must both guarantee that all
delivery messages reach their destination and that the messages are applied in the
same order that they are sent. Sybase SQL Remote incorporates a protocol to
guarantee reception of replication updates in the correct order.

9
Propagation methods

Connection-based replication: Replication Server


Some replication technologies rely on the presence of a continuous, or at
least almost continuous, connection between the databases. Through this
connection, the two databases conduct an ongoing dialogue. These types of
systems excel at replicating changes quickly. Indeed, given sufficient
resources and channel capacity, replication can occur reliably with a lag time
of no more than a few seconds.
Sybase Replication server is near real-time replication system designed
primarily for replication between a small number of databases. It is normally
used with a continuous, reliable, high-speed connection. It incorporates
store-and-forward techniques that allow replication to continue automatically
when a connection is lost and later re-established.
The main drawback of this type of system is that a reliable, continuous
connection can be expensive to maintain. This restriction makes connection-
based technologies suited to replication between two large, fixed databases.
In environments where the remote machines are mobile or are only
occasionally connected, message-based or session-based technologies
provide more flexible solutions.

10
Chapter 1 Sybase Replication Technologies

Sybase replication technologies


Sybase provides three replication technologies:
♦ MobiLink is a session-based technology intended for the two-way
replication of data between a central, consolidated database and a large
number of remote databases. It supports a variety of consolidated
database servers, including non-Sybase databases. Administration and
resource requirements at the remote sites are minimal, making it well
suited to a variety of mobile applications. At the end of each
synchronization session, the databases are consistent.
♦ SQL Remote is a message-based technology intended for the two-way
replication of transactions. It is designed for two-way replication
involving a consolidated data server and large number of remote
databases. Administration and resource requirements at the remote sites
are minimal, making it well suited to mobile databases. This system is
message based. Depending on the setup, typical lag times between the
consolidated and remote databases can be on the order of seconds,
minutes, or hours.
♦ Replication Server is a connection-based technology intended for the
two-way replication of transactions. It is well suited to replication
between a small number of enterprise databases connected by a high-
speed network, generally with an administrator at each site. In such a
setup, it is possible to achieve lag times as low as a few seconds.

Choosing a replication technology


Each Sybase replication technology lends itself to particular applications.
The following descriptions differentiate the technologies and let you select
the one best suited to your needs.
You should consider which of the following considerations are important in
your application
Your consolidated In a typical replication environment, a large database serves as a central
database system repository for information. Sometimes you can choose a database system that
suits your needs. Other times, a central database already exists and you must
adapt the replication system to work with it.
MobiLink can work with many popular database servers, including Sybase
Adaptive Server Anywhere, Sybase Adaptive Server Enterprise, Oracle,
Microsoft SQL Server, and IBM DB2.
In a SQL Remote installation, the central database must be either Sybase
Adaptive Server Anywhere or Sybase Adaptive Server Enterprise.

11
Sybase replication technologies

Your remote Sybase replication technologies also differ in the types of remote databases
database system that they can support. MobiLink allows your remote database to be either
Adaptive Server Anywhere or UltraLite.
SQL Remote supports only Adaptive Server Anywhere remote databases.
Network MobiLink and SQL Remote are both well suited to occasionally-connected
characteristics environments, where remote sites must operate for hours or days in isolation,
although more frequent synchronization is possible whenever a network
connection is available. In contrast, Replication Server is designed for a
continuous connection to allow large amounts of data to be replicated
promptly.
MobiLink is session based. A real-time connection is required during
synchronization. If this connection is interrupted before synchronization is
complete, the process will not complete until the next synchronization. In
contrast, SQL Remote relays information via messages, which can be sent or
received asynchronously. These messages may take the form of files on a
hard disk, or e-mail messages. These messages can be processed whenever
they are received, allowing replication to occur incrementally.
Latency In some situations, it may be important that your information is replicated
immediately. In others, replication once or twice a day may suffice. In fact,
more frequent replication may be impossible when no network connection is
available.
Both MobiLink and SQL Remote are primarily intended for situations where
replication occurs infrequently; for example every few hours, or days.
MobiLink and SQL Remote can both handle more frequent synchronization,
but resource and network requirements are greater. However, given sufficient
resources, MobiLink synchronizations can occur every few minutes.
SQL Remote, when run in continuous mode, allows replication to occur
every few seconds.
Replication Server is designed for setups requiring near real-time replication.
The number of If you have a very large number of remote users, the best options are
remote sites MobiLink or SQL Remote. The SQL Remote message-based design allows a
typical installation to handle thousands of remote users. MobiLink scalability
is limited only by the scalability of the consolidated database-management
system. Replication Server is designed for only a few sites.
While these numbers are guidelines, there is no hard limit as the maximum
number of remote sites with any of these systems. The actual number
depends on the amount of information replicated, the frequency of
synchronization, and the design of your application.

12
Chapter 1 Sybase Replication Technologies

Transaction SQL Remote replicates data by scanning the transaction log and preparing
ordering messages, as appropriate, for each transaction. It orders these messages and
sends them to the remote or consolidated site. When processing received
messages, SQL Remote always processes them in the same order as they
were applied to the other database. When necessary, it automatically delays
processing a message until all earlier messages have been applied.
MobiLink, in contrast, works by lumping the results of multiple transactions
on the remote database into one set of changes to be applied to the
consolidated database. Since synchronization always occurs at a transaction
boundary, referential integrity is preserved. The order of the individual
changes made during the component transactions is not preserved. However,
since uncommitted data is never synchronized, data integrity is preserved.
Achieving data Immediately following each synchronization session, the data in the two
consistency at a databases is consistent. The ability to guarantee the consistency of the data at
particular time a remote site at a particular point in time is an advantage of session-based
replication. For example, if it is important that the data at a remote site
accurately reflect the data in the consolidated database at a particular time,
say 10 o’clock in the morning, this objective can be achieved by
synchronizing just prior to this time. As long as the synchronization
completes successfully, the currency of the data at the remote site is assured.
When changes to the data are replicated through an exchange of messages, it
is difficult to guarantee that the data in a particular remote site is completely
consistent with the data in the consolidated site at any particular point in
time. For example, sometimes a message is lost in transit. SQL Remote
automatically recognizes this fault and resends the message, but such
interruptions can cause unexpected delays.

MobiLink characteristics
MobiLink is designed for replication installations with the following
requirements:
♦ Large numbers of databases MobiLink is designed to support large
numbers of remote databases. It can support thousands of remote
databases in a single installation.
♦ Occasionally connected MobiLink supports databases that are
occasionally connected or indirectly connected to the network on which
the server is running. MobiLink scalability is limited only by the
scalability of the consolidated database-management system.
♦ Medium to high latency Latency is the lag time between data being
entered at one database and being replicated to each database in the
installation. Applications typically connect and synchronize at periods of
minutes, hours, or days.
13
Sybase replication technologies

♦ Low to medium volume Download information for remote sites is


prepared for one remote site at a time. Large amounts of data in a
MobiLink system can cause long connection times, since the remote site
cannot disconnect until synchronization is complete.
♦ Heterogeneous databases MobiLink supports many of the most
popular relational-database systems for use as a consolidated database.
The schema of the remote sites can be different from that of the
consolidated database because you control the synchronization process
by writing scripts.

SQL Remote characteristics


SQL Remote is designed for replication installations with the following
requirements:
♦ Large numbers of databases SQL Remote is designed to support
large number of remote databases. It can support thousands of remote
databases in a single installation because the messages for many remote
sites can be prepared simultaneously.
♦ Occasionally connected SQL Remote supports databases that are
occasionally connected or indirectly connected to the network on which
the server is running.
♦ Low to high latency High latency means a long lag time between data
being entered at one database and being replicated to each database in
the installation. With SQL Remote, replication messages are sent
typically at periods of seconds, minutes, hours, or days.
♦ Low to moderate volume As replication messages are delivered
occasionally, a high transaction volume at each remote site can lead to a
very large volume of messages. SQL Remote is best suited to systems
with a relatively low volume of replicated data per remote database. At
the consolidated site, SQL Remote can, however, prepare messages
efficiently by preparing messages for multiple sites simultaneously.
♦ Homogeneous databases SQL Remote supports Adaptive Server
Enterprise and Adaptive Server Anywhere databases. Each database in
the system must have a very similar schema.

Replication Server characteristics


Replication Server is designed for replication installations with the following
requirements:

14
Chapter 1 Sybase Replication Technologies

♦ Small numbers of databases Replication Server is designed to


support replication among servers, with installations typically involving
fewer than one hundred servers.
♦ Continuously connected Connections between primary sites and
replicate sites may be over a wide area network, but Replication Server
is designed for situations where there is a near-continuous connection
path for data exchange among the servers in the installation.
♦ Low latency Low latency means a short lag time between data being
entered at one database and being replicated to each database in the
installation. With Replication Server, replication messages are sent
typically within seconds of being entered at a primary site.
♦ High volume With near-continuous connections and high
performance, Replication Server is designed for a high volume of
replication messages.
♦ Heterogeneous databases Replication Server supports several
leading DBMSs, and allows mapping of object names during replication,
so that support for heterogeneous databases is provided.

15
Sybase replication technologies

16
P A R T TW O

MobiLink Synchronization

This part describes the concepts, architecture, and features of MobiLink


synchronization technology. The material describes both Adaptive Server
Anywhere and UltraLite clients, as well as the use of consolidated databases
from a variety of vendors.

17
18
C H A P T E R 2

Introducing MobiLink Synchronization

About this chapter This chapter introduces you to the Sybase MobiLink synchronization
technology. It describes the purpose and defining characteristics of
MobiLink.
Contents
Topic Page
Overview 20
What’s new in 7.0 23
What’s new in 6.0.3 25

19
Overview

Overview
Most mobile and embedded applications require data to be uploaded to a
central database, downloaded from a central database, or both uploaded and
downloaded. This functionality is essential to making the application
function effectively within the information infrastructure of an organization.
Adaptive Server Anywhere and UltraLite applications are equipped with the
ability to synchronize data with a central database. Often, this task must be
accomplished through a low-bandwidth channel. To make the most of
limited channels, synchronization uses an efficient means of transferring
information between consolidated and remote databases. MobiLink is the
name of the technology that provides this synchronization functionality.
MobiLink synchronization technology, included in SQL Anywhere Studio, is
designed to work with industry-standard enterprise SQL database-
management systems from Sybase and other vendors.
MobiLink clients In a MobiLink setup, each mobile or embedded application has its own
database. These databases are called remote databases, and may be an
integral part of the application, as in the case of UltraLite applications, or
may be separate components, as is the case when using Adaptive Server
Anywhere.
These two types of remote databases, the ones within UltraLite applications
and Adaptive Server Anywhere databases, may also be referred to as
MobiLink clients because, in addition to the remote data, each type contains
logic that forms an integral part of the MobiLink replication system.
MobiLink clients automatically keep track of the changes made to the remote
database since the last synchronization with the central database. When the
remote database is next synchronized, all these changes are uploaded.
UltraLite clients automatically use internal logic to keep track of the
changes, using a separate field that records the status of each row. Adaptive
Server Anywhere clients automatically track the changes using their
transaction log.
Subset of the Mobile and embedded databases contain a fraction of the data that exists in
central data the central database. The central database is called the consolidated database
because it consolidates all the data throughout the MobiLink installation.
The tables in each remote database contain a subset of the data in the central
database. For example, a customer table might contain over 100 columns and
100,000 rows in the consolidated database, but the remote database may only
require 4 columns and 1000 rows. MobiLink technology allows you to define
the exact subset to be downloaded to each remote database.

20
Chapter 2 Introducing MobiLink Synchronization

MobiLink synchronization is flexible. You define the subset of data using the
native SQL dialect of the central database-management system. Tables in the
remote database may correspond to tables in the central database, or you may
reorganize the data using tables and rows more appropriate to the needs of
the remote application. You can populate a remote table from a consolidated
table with a different name, or even from a join of two or more tables.
When synchronizing, it is important to only transfer data that has changed
rather than a complete copy of the data. The MobiLink client automatically
keeps track of and uploads only data that has changed since the previous
synchronization. You control which data is downloaded to each client using
the native SQL dialect of the central database-management system. This
system ensures that only needed information is transferred.
Conflict resolution Mobile and embedded databases frequently share common data. They also
must allow updates to this data. When two or more remote databases update
the same row, the conflict cannot be prevented. Instead, it must be detected
and resolved when the changes are uploaded to the central database.
MobiLink synchronization automatically detects these conflicts. You
implement the conflict resolution logic using the native SQL dialect of the
central DBMS.
Encryption When the remote and consolidated databases are far apart, replication may be
possible only over a public network. To ensure your privacy, MobiLink
technology supports strong encryption of all communication between the
remote databases and the MobiLink synchronization server.
The MobiLink A MobiLink client synchronizes with a central, consolidated database
synchronization through a MobiLink synchronization server. This server provides an
server interface between the communications from the remote application and the
central, consolidated database server.

21
Overview

consolidated
database server

consolidated
data store

ODBC

MobiLink client MobiLink


(Adaptive Server
synchronization
Anywhere or an
server
UltraLite application)

TCP/IP* TCP/IP*

* Other communication protocols are also supported.

You control the synchronization process using scripts. These scripts are SQL
statements or procedures written in the native language of the consolidated
DBMS. For example, you can use a SELECT statement to identify the
columns and tables in the consolidated database that correspond to each
column of a row uploaded from a table in your remote database. These
scripts are stored in tables within the consolidated database. Each script
controls a particular event during the synchronization process.
Synchronization Synchronization can occur through a variety of streams. One option is a
streams TCP/IP connection between the application and the MobiLink
synchronization server. Other platforms require different solutions. For
example, UltraLite applications on the Palm Computing Platform can use
HotSync, ScoutSync, HTTP, TCP/IP, or direct serial port communication.
Regardless of the stream, you control the synchronization process using the
same SQL scripts defined in your consolidated database.
$ For a detailed introduction to MobiLink synchronization, see
"Synchronization Basics" on page 27.

22
Chapter 2 Introducing MobiLink Synchronization

What’s new in 7.0


Following is a list of changes and additions to the software since
version 6.0.3.
♦ Adaptive Server Anywhere clients MobiLink technology now
supports Adaptive Server Anywhere as a client, as well as UltraLite
applications.
$ For more information, see "Adaptive Server Anywhere Clients" on
page 131.
♦ mlxtract creates Adaptive Server Anywhere client databases
mlxtract creates Adaptive Server Anywhere databases, suitable for use
as MobiLink clients, using an Adaptive Server Anywhere reference
database as a template.
♦ Synchronization script versions Synchronization scripts can now be
grouped by assigning a script version name with each script. This feature
allows the MobiLink synchronization server to respond differently when
synchronizing different types of applications, or different versions of the
same application.
♦ New data types LONG BINARY and LONG VARCHAR data types
can now be replicated using MobiLink technology.
♦ New HotSync conduit A new HotSync conduit allows HotSync
synchronization with a centrally located MobiLink synchronization
server. The MobiLink synchronization server no longer needs to be on
the same machine as the HotSync manager is.
♦ ScoutSync conduit UltraLite applications for the Palm Computing
Platform can now synchronize using ScoutSync technology, available
from Riverbed Technologies.
♦ report_error script A new script provides a convenient way to report
errors during synchronization. The report_error script also makes
debugging the behavior of the handle_error script much easier. The
report_error script has the same parameters as the handle_error script,
except that the first parameter is the action code returned by
handle_error.

23
What’s new in 7.0

Behavior changes
♦ New table and script names The tables that hold synchronization
scripts and related information in the consolidated database now have
new names. Previously, these table names began with the prefix ul_.
This prefix has been changed to ml_. Older consolidated databases must
be upgraded for compatibility with version 7.0.
Similarly, the stored procedure that facilitates adding table scripts has
been renamed from sp_table_script to ml_add_table_script and the
stored procedure that facilitates adding connection scripts has been
renamed from sp_connection_script to ml_add_connection_script.
Under DB2, these names are truncated to 18 characters.
♦ dbssrv7 is now called dbmlsrv7 The name of the command that
starts the MobiLink synchronization server is now called dbmlsrv7.
Likewise, the command that stops this server is now called dbmlstop.
♦ Synchronization scripts require a version name Synchronization
scripts must now be assigned a script version name. Script version
names allow the MobiLink synchronization server to treat different
clients differently.

Upgrade issues
Subject to the issues the above behavior changes, older versions of UltraLite
applications can synchronize with the new version of the MobiLink
synchronization server. However, Adaptive Server Anywhere databases and
new UltraLite applications are incompatible with older versions of the
MobiLink synchronization server.
Old consolidated database can be upgraded using included scripts.

24
Chapter 2 Introducing MobiLink Synchronization

What’s new in 6.0.3


Following is a list of changes and additions to the software since
version 6.0.2.
♦ New data types Real and double data types are now fully supported.
♦ ODBC 3.51 The MobiLink synchronization server now uses
ODBC 3.51, in common with the rest of Adaptive Server Anywhere.
Version 6.0.2 of the MobiLink synchronization server used ODBC 2.0.
♦ Character set translation The MobiLink synchronization server now
translates all uploaded characters to Unicode and passes them to the
consolidated database using the Unicode ODBC API. Conversely, it
translates all downloaded characters from Unicode to the character set of
your UltraLite application. Character set translation within the
consolidated database server can influence the results, but the new
system allows more consistent behavior across multiple platforms.
$ For more information, see "Character-set translation during
synchronization: Windows" on page 48.
♦ Free technical advice Technical advice and limited support is
available for free on the newsgroup sybase.public.sqlanywhere.mobilink.
The host for this newsgroup is forums.sybase.com.
♦ MobiLink synchronization server runs as a Windows NT service
When you run the MobiLink synchronization server as a service, you
can configure it to continue running when you log off the Windows NT
workstation.
$ For more information, see "Running MobiLink synchronization
server as Windows services" on page 41.
♦ DB2 setup scripts provided To make it easier to use IBM DB2 as a
consolidated database, a DB2 setup script has been added to the
available set scripts.
$ For a list of setup scripts, see "Creating a consolidated database"
on page 38.

Behavior changes
♦ Location of synchronization scripts changed The synchronization
scripts for non-Adaptive Server Anywhere databases are now installed
into the MobiLink\setup subdirectory of your Adaptive Server Anywhere
installation directory.

25
What’s new in 6.0.3

Upgrade issues
Older versions of UltraLite applications can synchronize with the new
version of the MobiLink synchronization server. However, new UltraLite
applications cannot synchronize with older versions of the MobiLink
synchronization server.

26
C H A P T E R 3

Synchronization Basics

About this chapter This chapter describes the MobiLink technology, which provides a
synchronization mechanism for Adaptive Server Anywhere client databases
and UltraLite applications.
Contents
Topic Page
Parts of the synchronization system 28
The MobiLink synchronization server 29
MobiLink clients 30
The synchronization process 32
The consolidated database 35
Creating a consolidated database 38
Running the MobiLink synchronization server 40
Details of the synchronization process 43
Character-set considerations 48
Transport-layer security 51

27
Parts of the synchronization system

Parts of the synchronization system


The following diagram displays the components of the synchronization
system. The communications channel between the application and the
MobiLink synchronization server can be any of the supported
communication protocols. These protocols include TCP/IP, HTTP, Serial,
and HotSync, although some protocols are not available on all platforms.

consolidated
database server

consolidated
data store

ODBC

MobiLink client MobiLink


(Adaptive Server
synchronization
Anywhere or an
server
UltraLite application)

TCP/IP* TCP/IP*

* Other communication protocols are also supported.

28
Chapter 3 Synchronization Basics

The MobiLink synchronization server


The MobiLink synchronization server provides an interface between the
consolidated database and the remote clients. The synchronization server
communicates with a consolidated database server via ODBC. It can
communicate with MobiLink clients using a number of popular protocols
over various types of networks.
Given sufficient resources, many remote applications can synchronize
simultaneously, making MobiLink synchronization well suited to large-scale
deployment.
Because the MobiLink synchronization server is a separate component, it is
not tied to one database product. It can communicate with a number of
commercially available database servers, including Sybase Adaptive Server
Anywhere, Sybase Adaptive Server Enterprise, Oracle, IBM DB2, and
Microsoft SQL Server.
Synchronization The MobiLink synchronization server contains most of the synchronization
logic is stored in logic. This server is connected to a consolidated database server that serves
the consolidated as the central repository for all the replicated data.
database
You store synchronization information, including synchronization scripts, in
the consolidated database. These scripts guide the MobiLink synchronization
server in handling connections with remote users and in matching data in the
remote databases with that in the consolidated database.

Development tip
You can use a single Adaptive Server Anywhere database as both
reference and consolidated database during development. You can switch
the consolidated database later, if necessary.

$ For information about the reference database, see "Preparing a


reference database" on page 64 of the book UltraLite Developer’s Guide.
$ For information about the consolidated database, see "The consolidated
database" on page 35.

29
MobiLink clients

MobiLink clients
The remote applications in a MobiLink setup are referred to as MobiLink
clients because, in addition to the remote data, each contains logic that forms
an integral part of the MobiLink replication system. In particular, a
MobiLink client must contain logic to keep track of changes to the database,
to prepare data to send to the server, and to incorporate data that it receives
in reply.
Two types of MobiLink clients are presently available:
♦ Adaptive Server Anywhere MobiLink client logic is built into
Adaptive Server Anywhere, allowing it to be used as clients.
♦ UltraLite applications Applications built with the UltraLite technology
available in Adaptive Server Anywhere are automatically MobiLink
enabled whenever the application includes a call to the appropriate
MobiLink synchronization function.

UltraLite MobiLink clients


If it is an UltraLite application that forms part of your MobiLink setup, the
UltraLite development tools, included in SQL Anywhere Studio,
automatically include the necessary logic when you build your UltraLite
application.
Since the runtime handles the synchronization actions at the application end,
you can write your application with little regard to synchronization. The
UltraLite runtime keeps track of changes made since the previous
synchronization.
Synchronization can take place through HotSync, ScoutSync, TCP/IP,
HTTP, or direct serial port communication. You must connect and configure
one of these communications channels.
Initiating Synchronization is initiated from your application by a single call to the
synchronization ULSynchronize function when using TCP/IP, HTTP, or serial port
from an UltraLite synchronization. The interface for HotSync is slightly different.
application
Once synchronization is initiated from the application or from HotSync, the
MobiLink synchronization server and the UltraLite runtime control the
actions that occur during synchronization.
$ For more information on initiating synchronization, see "Adding
synchronization to your application" on page 74 of the book UltraLite
Developer’s Guide.

30
Chapter 3 Synchronization Basics

$ For details of how to implement synchronization on each platform, see


"Platform-Specific Development" on page 205 of the book UltraLite
Developer’s Guide.

Adaptive Server Anywhere MobiLink clients


Adaptive Server Anywhere clients must be configured to work with
MobiLink synchronization. Although the logic is included, you must define
which columns, rows, or tables are to be included in the synchronization
process.
Using appropriate definition statements, you can identify the data that is to
be synchronized with a particular synchronization server. You can choose to
synchronize all or some of the data with one MobiLink synchronization
server, or specify that some data is to be synchronized with one server and
other data with another server.
Initiating Synchronization is initiated by running a command-line utility called
synchronization dbmlsync. This utility connects to the remote database and prepares the
from Adaptive upload stream using information contained in the transaction log of the
Server Anywhere remote database. It then uses information stored in a synchronization
definition, contained in the remote database, to connect to the MobiLink
synchronization server and exchange data.
$ For more information about Adaptive Server Anywhere clients, see
"Adaptive Server Anywhere Clients" on page 131.

The synchronization user name


The ml_user table holds a list of MobiLink client user names. It also
records the synchronization state of each user in the commit_state column or
the progress column. This information allows proper recovery if
synchronization is interrupted.
The user name uniquely identifies each MobiLink client. If a client attempts
to synchronize, but the user identification it carries is absent from the user
table, the MobiLink synchronization server automatically inserts a new row.
For this reason, you do not need to take any action to maintain this table.

31
The synchronization process

The synchronization process


To synchronize, a remote device must establish a connection with a
MobiLink synchronization server, which in turn maintains a pool of
connections to a database server and hence the consolidated database. The
synchronization process happens in several steps, depicted in the following
diagram.

database server

consolidated
data store

1. upload rows ODBC

MobiLink
MobiLink TCP TCP
2. download rows synchronization
client /IP* /IP*
server

3. confirm receipt

* Other communication protocols are also supported.

The upload stream To upload rows, MobiLink clients prepare and send an upload stream that
and the download contains a list of all the rows that have been updated, inserted, or deleted on
stream the MobiLink client since the last synchronization. Similarly, to download
rows, the MobiLink synchronization server prepares and sends a download
stream that contains a list of inserts, updates, and deletes. These two streams
are part of steps 1 and 2, respectively, in the synchronization process.

32
Chapter 3 Synchronization Basics

Steps in the synchronization process


The synchronization process proceeds as follows. Each step in the following
description is divided into two parts. One part describes the actions of the
MobiLink client; the other part describes the actions of the MobiLink
synchronization server.
1 The MobiLink client automatically keeps track of which rows on the
remote device have been inserted, updated, or deleted since the previous
successful synchronization. The MobiLink client establishes a
connection with the MobiLink synchronization server and uploads these
changes. These actions are initiated by the MobiLink client.
The upload stream consists of a set of single-row inserts, updates, and
deletes.
The MobiLink synchronization server receives and applies the upload
stream instructions to the consolidated database. The changes are made
in a single transaction. When finished, the MobiLink synchronization
server commits the transaction in the consolidated database.
2 The MobiLink synchronization server compiles a list of rows to be
inserted, updated, or deleted on the MobiLink client, by executing the
scripts present in the consolidated database. It sends these rows back to
the MobiLink client in the form of a download stream.
The MobiLink synchronization server prepares this download stream
using a single transaction in the consolidated database, but it does not
commit any changes until the application confirms receipt. You can use
this transaction to maintain a record of which information has been sent
to each remote database.
The MobiLink client is assured that all the changes it sent to the server
in the upload stream have been committed in the consolidated database
when it starts to receive the download stream.
The MobiLink client automatically updates its record of which data is
modified so that the same changes are not sent again. It then processes
the download stream, deleting old rows, inserting new rows, and
updating rows that have changed. It makes all these changes in a single
transaction in its own database. When finished, it commits the
transaction.
3 The MobiLink client sends a short message back to the MobiLink
synchronization server, confirming that it has received and processed all
the changes.
The MobiLink synchronization server commits the download
transaction in the consolidated database upon receipt of this
confirmation.

33
The synchronization process

During MobiLink synchronization, there are few distinct exchanges of


information. The entire upload stream is built and sent from the remote site
and, in response, the entire download stream is built and sent from the
MobiLink synchronization server. Limiting the chattiness of the protocol is
especially important when communication is slower and has higher latency,
as is the case when using telephone lines or public wireless networks.
$ For a more detailed description of the synchronization process, see
"Scripts and the synchronization process" on page 62.

Built-in automation and communications fault recovery


Built-in automation frees you from routine implementation tasks. For
example, the MobiLink client automatically keeps track of the rows in each
table that have been inserted, updated, or deleted since the last
synchronization. When you synchronize, the MobiLink client automatically
identifies the new, modified, or deleted rows and uploads each to the
MobiLink synchronization server.
During the synchronization process, state information is maintained in both
the application and the MobiLink synchronization server. Should the
synchronization be interrupted, both the MobiLink synchronization server
and application retain information regarding their own states. Upon the next
attempt to synchronize, they automatically continue synchronization where
they left off, without explicit direction.

34
Chapter 3 Synchronization Basics

The consolidated database


Applications synchronize with a central, consolidated database. It is often
convenient to make the schema of the remote databases similar to the schema
of the consolidated database. Indeed, one way to design the application
database is to use the schema of the consolidated database as a starting point.
In the consolidated database, you may already have tables that correspond to
each of the remote tables.
Consolidated and While the reference database you use to build your application must be an
reference Adaptive Server Anywhere database, you can build a consolidated database
databases using any supported ODBC-compliant product. You can use a Sybase
product, such as Adaptive Server Anywhere or Adaptive Server Enterprise,
or you can use a product sold by other companies, such as Oracle, IBM DB2,
or Microsoft SQL Server. A single Adaptive Server Anywhere database can
fulfill both reference and consolidated roles.

Consolidated database server requirements


MobiLink synchronization was designed to work with Sybase database
products as well as other ODBC-supporting database-management systems,
such as Oracle, IBM DB2, and Microsoft SQL Server. You can use the
synchronization scripts to exploit the features of your particular consolidated
server.
The MobiLink synchronization server can handle multiple simultaneous
synchronization requests. It does so by maintaining a pool of connections
with the database server and temporarily assigning these as required when
remote devices connect and synchronize.
When running in a production environment, you may want to keep the
MobiLink synchronization server connected to the database server
indefinitely, even if is inactive for long periods of time. You should disable
any feature that disconnects client applications after a certain period of
inactivity. On Adaptive Server Anywhere, you should set the database server
-ti command-line option to zero to prevent the server from disconnecting
the MobiLink synchronization server if it is inactive for a significant length
of time.
$ For information on the -ti command-line, see "–ti command-line
option" on page 34 of the book ASA Reference.

35
The consolidated database

How remote tables relate to consolidated tables


Synchronization designs can specify an arbitrary mapping between tables
and rows in the remote database and tables and rows in the consolidated
database. The only restriction is that columns containing the same data in the
consolidated database be compatible in type with those in the application.
Corresponding columns would usually be of the same type, but automatic or
explicit type conversion can be used, if necessary.
Arbitrary Tables present in a remote database need not exist in the consolidated
relationships database. Synchronized data in one remote application table can be
permitted distributed between columns in different tables, even between tables in
different consolidated databases. You specify these arbitrary relationships
using the synchronization scripts.
Direct relationships Although complicated schemes are possible, you can often simplify your
are simple design by using a table structure in the remote database that is a subset of
that in consolidated database. Using this method, every table in the remote
database exists in the consolidated database. Corresponding tables have the
same structure and foreign key relationships.
Tables in the consolidated database will frequently contain extra columns
that are not synchronized. Indeed, extra columns can aid synchronization.
For example, a timestamp column can identify new or updated rows in the
consolidated database. In other cases, extra columns or tables in the
consolidated database may hold information that is not required at remote
sites.

MobiLink system tables


You direct the actions of the MobiLink synchronization server by writing
scripts. These scripts are stored in tables that must reside in the consolidated
database. An additional table contains information about each remote user.
These tables have the following structure.

36
Chapter 3 Synchronization Basics

ml_table ml_user
table_id <pk> integer user_id <pk> integer
name <ak> varchar(128) name varchar(128)
commit_state integer

ml_scripts_modified
table_id = table_id last_modified datetime

ml_table_script
version_id <pk,fk> integer version_id = version_id
table_id <pk,fk> integer
event <pk> varchar(128)
script_id <fk> integer
ml_script_version
script_id = script_id version_id <pk> integer
name varchar(128)
description text
ml_script
script_id <pk> integer
script text version_id = version_id

ml_connection_script
version_id <pk,fk> integer
script_id = script_id event <pk> varchar(128)
script_id <fk> integer

* Under IBM DB2, the table names ml_scripts_modifie and ml_connection_scri are used,
due to the 18 character limit.

IBM DB2 only supports column names and other identifiers of 18 characters
or less. MobiLink system tables are truncated where necessary.
These tables have the same structure in non-Sybase database-management
systems, but the columns are of equivalent, native types.

37
Creating a consolidated database

Creating a consolidated database


To create a database that can be used as a MobiLink consolidated database,
you must install the MobiLink system tables. Setup scripts are provided for
Sybase Adaptive Server Anywhere, Sybase Adaptive Server Enterprise,
Oracle 8, Microsoft SQL Server, or IBM DB2.
Install the system The way you install the MobiLink system tables depends on the DBMS you
tables wish to use as a consolidated database.
♦ Adaptive Server Anywhere Create an Adaptive Server Anywhere
database. The MobiLink system tables are created automatically. If you
are using this database as a reference database also, do not disable Java
support. If you have a database created with an earlier version of
Adaptive Server Anywhere, you can run the Upgrade utility to carry out
this task.
♦ Sybase Adaptive Server Enterprise Run the syncase.sql SQL script,
located in the MobiLink\setup subdirectory of your SQL Anywhere
installation.
♦ Microsoft SQL Server Run the syncmss.sql SQL script, located in the
MobiLink\setup subdirectory of your SQL Anywhere installation.
♦ Oracle Run the syncora.sql SQL script, located in the MobiLink\setup
subdirectory of your SQL Anywhere installation.
♦ IBM DB2 Run the syncdb2.sql SQL script, located in the
MobiLink\setup subdirectory of your SQL Anywhere installation.
The syncdb2.sql script has a default connection statement connect to
DB2Database. You should make a copy of the script and alter this line
to be appropriate for your installation.
Also, there are columns that require a LONG tablespace. If there is no
default LONG tablespace, the creation statements for the tables
containing these columns must be qualified appropriately, as in the
following example.
CREATE TABLE ... ( ... )
IN tablespace
LONG IN long-tablespace
The stored procedures in syncdb2.sql are implemented in Java in the
associated file SyncDB2.class. The source code is provided in
SyncDB2.java. The script uses the tilde character (~) as command
delimiter.
The default tablespace (usually called USERSPACE1) of a DB2
database that you wish to use as a consolidated database must use 8 kb
pages.
38
Chapter 3 Synchronization Basics

$ For an example using the sample application, see "Creating a DB2


consolidated database for CustDB" on page 90.
$ For instructions on running scripts, see the documentation for your
DBMS.
Create an ODBC To carry out synchronization, the MobiLink synchronization server needs an
data source ODBC connection to your consolidated database. You must have an ODBC
driver for your server, and create an ODBC data source for the database on
the machine on which your MobiLink synchronization server is running.
$ For information on starting the MobiLink synchronization server, see
"Running the MobiLink synchronization server" on page 40.
Create You need to design and write synchronization scripts, and store them in your
synchronization consolidated database. You can do this from Sybase Central. Sybase Central
scripts requires a JDBC or ODBC connection to your database.
Synchronization scripts are written in the SQL dialect of the consolidated
database.
$ For information on designing and writing synchronization scripts, see
"Writing Synchronization Scripts" on page 57.
$ For information on adding scripts to your database with Sybase Central,
see "Adding scripts to your consolidated database" on page 68.

39
Running the MobiLink synchronization server

Running the MobiLink synchronization server


All MobiLink clients synchronize through the MobiLink synchronization
server. None can connect directly to a database server. You must start the
MobiLink synchronization server before asking a MobiLink client to
synchronize.
$ For information about synchronization using HotSync, see
"Configuring synchronization for Palm devices" on page 221 of the book
UltraLite Developer’s Guide.
You can start the MobiLink synchronization server in the following ways:
♦ as an executable—see "Starting the MobiLink synchronization server"
on page 40
♦ as a Windows NT service—see "Running MobiLink synchronization
server as Windows services" on page 41

Starting the MobiLink synchronization server


The MobiLink synchronization server opens connections, via ODBC, with
your consolidated database server. It then accepts connections from remote
applications and controls the synchronization process.

v To start the MobiLink synchronization server


♦ Run the command-line utility dbmlsrv7. Use the –c switch to specify
the ODBC connection parameters for your consolidated database.
You must specify the database connection parameters. Other switches are
available, but optional.
$ For a list of connection parameters, See "MobiLink synchronization
server" on page 150.
Example ♦ The following command starts the MobiLink synchronization server,
identifying the ODBC data source UltraLite Sample 7.0 as the
consolidated database. Enter the entire command on one line.
dbmlsrv7
-c "DSN=UltraLite Sample 7.0;UID=dba;PWD=sql"
–o mlsync.log
-vcr
-x tcpip

40
Chapter 3 Synchronization Basics

The above command uses the –o switch to specify that the log file
should be named mlsync.log. The contents of this file are verbose
because of the –v switch and parameters. The –x switch specifies that
MobiLink clients will be permitted to connect via TCP/IP. Replace the
word tcpip with the word serial if your applications use a serial
connection.

v To stop the MobiLink synchronization server


♦ Execute the command-line utility dbmlstop on the machine on which the
MobiLink synchronization server is running.
dbmlstop

The server will shut down, possibly following a short delay.

Running MobiLink synchronization server as Windows services


You can run the MobiLink synchronization server as a service under
Windows NT. In some circumstances, this mode has security and ease-of-
administration benefits.
When you start a program as an executable, it runs under your Windows NT
login session. When you log off, the program terminates. Only one person
logs onto Windows NT, on any one computer, at one time. If you wish to
keep a program running much of the time, as is commonly the case with
database servers, you must stay logged onto the computer. Staying logged
onto the computer can present a security risk, if the computer is left
unattended.
By running the MobiLink synchronization server as a service, it can run after
you log off the machine. In addition, you can configure the service to start up
automatically when Windows NT is started.

v To run the MobiLink synchronization server as a service


1 Start Sybase Central. From the Windows NT Start button, choose
Programs➤Sybase➤Sybase Central.
2 In the left pane, under MobiLink Synchronization, open the Services
folder. Double-click Add Service in the right pane.
3 Select MobiLink Synchronization Server from the list. Follow the
instructions in the wizard.
$ For more information on configuring services, and accommodating
service dependencies, see "Running the server outside the current session" on
page 18 of the book ASA User’s Guide.

41
Running the MobiLink synchronization server

Logging MobiLink synchronization server actions


You can control the operation of the MobiLink synchronization server using
its command-line options. Logging the actions that the server takes is
particularly useful during the development process, and when
troubleshooting.
Logging output to a Logging output is sent to the MobiLink synchronization server window. In
file addition, you can send the output to a log file using the -o command-line
option. The following command sends output to a log file named mlsync.log.
dbmlsrv7 -o mlsync.log -c ...

Controlling the You can control the amount of output that is logged using the -v command-
amount of logging line option. This option switches on verbose logging, and takes one or more
output of the following modifiers:
♦ –vc Log the contents of scripts. This implies -vs.
♦ –vn Log row counts.
♦ –vr Log row values and row processing.
♦ –vs Log script names.
♦ –vt Log translated script contents.
These switches can be used in combination. For example, the following
command logs the names of scripts, and the row values as they are
processed.
dbmlsrv7 -o mlsync.log -vsr -c ...

42
Chapter 3 Synchronization Basics

Details of the synchronization process


This section describes in more detail some important aspects of
synchronization, including the tasks that are carried out automatically by the
MobiLink client, and by the MobiLink synchronization server.
The information in this section is not required in order to implement simple
MobiLink synchronization designs, but it is useful as you move to more
robust and demanding synchronization schemes.
$ For an overview of the three-step synchronization process, see "The
synchronization process" on page 32.

Transactions in the synchronization process


The MobiLink synchronization server incorporates changes uploaded from
each remote application into the consolidated database in one transaction.
Changes to the consolidated database occur primarily as a result of uploaded
information in step 1, the MobiLink synchronization server commits these
results once it is through inserting new rows, deleting old rows, making
updates, and resolving any conflicts.
The MobiLink synchronization server prepares the download stream,
including all deletes, inserts, and updates, using another transaction. It does
not commit this transaction until it receives a positive confirmation from the
MobiLink client. If the client confirms a successful download, the MobiLink
synchronization server commits the download transaction. If the application
encounters problems or cannot reply, the MobiLink synchronization server
instead rolls back the download transaction.

Do not commit or rollback transactions within a script


COMMIT or ROLLBACK statements within scripts would alter the
transactional nature of the synchronization steps, and are not allowed.

Tracking The primary role of the download transaction is to select rows in the
downloaded consolidated database. However, you can use the download transaction to
information track the information downloaded to each remote device. For example, the
download transaction could update a timestamp that records the time of the
last download to a particular MobiLink client. During the next
synchronization, only rows updated since the previous download need be
sent. If the rows are not downloaded successfully, the download transaction
is rolled back and your last download timestamp remains accurate.

43
Details of the synchronization process

The MobiLink synchronization server uses two other transactions, one at the
beginning of synchronization, and one at the end. These transactions allow
you to record information regarding each synchronization and its duration.
Thus, you can record statistics about attempted synchronizations, successful
synchronizations, and the duration of synchronizations. Since data is
committed at various points in the process, these transactions also let you
commit data useful when analyzing failed synchronization attempts.
Similarly, the MobiLink client processes information in the download stream
in one transaction. Rows are inserted, updated, and deleted to bring the
remote database up to date with the consolidated data.

How synchronization failure is handled


MobiLink synchronization is fault tolerant. For example, if a communication
link fails during synchronization, both the remote database and the
consolidated database are left in a consistent state. In an UltraLite
application, the SQLCode is set to SQLE_COMMUNICATION_ERROR
when ULSynchronize returns.
There are three cases that are handled in different ways
♦ Failure during upload If the failure occurs while building the upload
stream, the remote database is left in exactly the same state as at the start
of synchronization. At the server, any part of the upload stream that has
been applied will be rolled back.
♦ Failure between upload and download If the failure occurs once the
upload stream is complete, but before the MobiLink client receives the
download stream, the remote database is left in an uncertain state. At the
server, the upload stream might be fully applied and committed, or the
failure may have occurred before the server applied the entire upload
stream. The MobiLink synchronization server automatically rolls back
incomplete transactions.
The next time the MobiLink client synchronizes, it determines the fate
of the previous upload stream before building the new upload stream. If
the previous upload was not committed, the new upload stream contains
all changes from the previous upload stream.
♦ Failure during download If the failure occurs in the remote device
while applying the download stream, any part of the download that has
been applied is rolled back and the remote database is left in the same
state as before the download. The MobiLink synchronization server
automatically rolls back the download transaction in the consolidated
database.

44
Chapter 3 Synchronization Basics

How the upload stream is processed


When the MobiLink synchronization server receives an upload stream from a
MobiLink client, the entire upload stream is stored until the synchronization
is complete. This is done for three purposes.
♦ Deadlock When an upload stream is being applied to the consolidated
database, it may encounter deadlock due to concurrency with other
transactions. These transactions might be upload transactions from other
MobiLink synchronization server database connections, or transactions
from other applications using the consolidated database. When an
upload transaction is deadlocked, it is rolled back and the MobiLink
synchronization server automatically starts applying the upload stream
from the beginning again.

Performance tip
It is important to write your synchronization scripts to avoid
contention as much as possible. Contention will have a significant
impact on performance when multiple users are synchronizing
simultaneously.

♦ Filtering download rows The most common technique for


determining rows to download is to download rows that have been
modified since the previous download. When synchronizing, the upload
precedes the download. Any rows inserted or updated during the upload
will be rows that have been modified since the previous download.
It would be difficult to write a download_cursor script that omits from
the download stream rows that were sent as part of the upload. For this
reason, the MobiLink synchronization server automatically removes
these rows from the download stream. When a row is being added to the
download stream, the MobiLink synchronization server locates the row
in the upload stream and omits the row from the download stream when
it is found to be the same.
♦ Processing deletes after inserts and updates The upload stream is
applied to the consolidated database in an order that avoids referential
integrity violations. The upload stream is formatted so all operations
(inserts, updates, and deletes) for a single table are grouped together.
The tables in the upload stream are ordered based on foreign key
relationships. All tables in the remote database that are referenced by
another table in the remote database will be in the upload stream before
the referencing table.
For example, if table A and table C both have foreign keys that reference
a primary key column in B, then table B rows are uploaded first.

45
Details of the synchronization process

When the upload stream is applied to the consolidated database, the


inserts and updates are applied in the order they appear in the upload
stream. When an inserted or updated row references a newly inserted
row, this ensures the referenced row will be inserted before the
referencing row. Deletes are applied in the opposite order after all inserts
and updates have been applied. When a row being deleted references
another row that is also being deleted, this order of operations ensures
the referencing row is deleted before the referenced row is deleted.

Referential integrity and synchronization


All MobiLink clients enforce referential integrity when they incorporate the
download stream into the remote database.
Rather than failing the download transaction, the MobiLink client
automatically deletes all rows that violate referential integrity.
This feature affords you these key benefits.
♦ Protection from mistakes in your synchronization scripts. Given the
flexibility of the scripts, it is possible to accidentally download rows that
would break the integrity of the remote database. The MobiLink client
automatically maintains referential integrity without requiring
intervention.
♦ You can use this referential integrity mechanism to delete information
from a remote database efficiently.

Referential integrity The MobiLink client incorporates changes from the download stream in a
checked at the end single transaction. To offer more flexibility, referential integrity checking
of the transaction occurs at the end of this transaction. Because checking is delayed, the
database may temporarily pass through states where referential integrity is
violated as rows are inserted, updated, and deleted, but the rows that violate
referential integrity are automatically removed before the download is
committed.
Errors are avoided The MobiLink client resolves referential integrity violations automatically.
This feature minimizes administration requirements. It also prevents an error
in a synchronization script from disabling an MobiLink client.
An efficient means You can exploit the automatic referential integrity mechanism of MobiLink
to delete rows clients to delete large quantities of information in a very efficient manner. If
your MobiLink client contains a primary row, and other rows that reference
it, you can delete all the referencing rows simply by synchronizing a delete
of the primary row.

46
Chapter 3 Synchronization Basics

Example Suppose that an UltraLite sales application contains, among others, the
following two tables. One table contains sales orders. Another table contains
items that were sold in each order. They have the following relationship.

sales_order
sales_order_items
id <pk>
id <pk,fk>
cust_id
line_id <pk>
order_date
id = id prod_id
fin_code_id
quantity
region
ship_date
sales_rep

If you use the download_deletes_cursor for the sales_order table to delete


an order, the automatic referential integrity mechanism automatically deletes
all rows in the sales_order_items table that point to the deleted sales order.
This arrangement has the following advantages.
♦ You do not require a sales_order_items script, because rows from this
table will be deleted automatically.
♦ The efficiency of synchronization is improved. You need not download
rows to delete from the sales_order_item table. If each sales order
contains many items, the performance improves because the download
stream is now smaller. This technique is particularly valuable when
using slow communication methods.

47
Character-set considerations

Character-set considerations
Each character of text is represented as a binary number. The mapping from
characters to binary codes is called the character set. Some character sets
rely on single-byte numbers. Others, such as Unicode, use double byte
numbers. Because they use twice the storage space for each character, they
can represent a much larger number of characters.
When the character set of your MobiLink client database is the same as your
consolidated database, character translation issues are avoided. The
characters you type can be transferred reliably.
Errors can occur or data can be lost when text using one character set must
be translated to another character set. Not all characters can be represented in
all character sets. In particular, single-byte character sets can represent a
much smaller number of characters than multi-byte systems because of the
limited number of codes available.
Most text needs to be sorted to build indexes and to prepare ordered result
sets, such as directory listings. The sort order identifies the order of the
characters. For example, a sort order typically states that the letter a comes
before the letter b, which comes before the letter c.
Each database has a collation sequence. You set the collation sequence
when you create the database, although how you do so can differ between
database systems. The collation sequence defines both the character set and
the sort order for that database.

Tip
Whenever possible, define the collation sequence of your reference
database to be the same as that of your consolidated database. Doing so
ensures that the collation sequence of your MobiLink client database will
match that of your consolidated database as closely as possible. This
arrangement reduces the chance of erroneous translations.

$ For more information, see "Character sets in UltraLite" on page 56 of


the book UltraLite Developer’s Guide.

Character-set translation during synchronization: Windows


During synchronization, characters may need to be translated from one
character set to another. The following translations occur as characters are
passed between the remote application and the consolidated database.

48
Chapter 3 Synchronization Basics

Character-set The MobiLink client sends data to the MobiLink synchronization server
translation during using the character set of the remote database.
upload
1 The MobiLink synchronization server communicates with the
consolidated database using the Unicode ODBC API. To do so, the
MobiLink synchronization server translates all characters received from
the remote database into Unicode.
2 If necessary, the ODBC driver for the consolidated database server
translates the characters from Unicode into the character set of your
consolidated database. This translation is controlled solely by the ODBC
driver for your consolidated database system. Hence, behavior can differ
between two different database systems, particularly systems made by
different manufacturers. MobiLink synchronization works with a
number of database systems. Check the documentation of your particular
consolidated server for details.

Character-set 1 The ODBC driver for the consolidated database system receives
translation during characters in the coding of the consolidated database. It translates these
download characters into Unicode to pass them through the Unicode API to the
MobiLink synchronization server. This translation is controlled solely
by the ODBC driver for your consolidated database system. Check the
documentation of your particular consolidated server for details.
2 The MobiLink synchronization server receives characters through the
Unicode ODBC API. If the remote database uses a different character
set, the MobiLink synchronization server translates the characters before
downloading them.

Examples ♦ UltraLite applications on Windows CE devices use the Unicode


character set.
When you synchronize a Window CE application, no character
translation occurs within the MobiLink synchronization server. The
server finds that data arriving from the application is already in Unicode
and passes it directly to the ODBC driver. Similarly, no character-set
translation is necessary when downloading data.
♦ All Adaptive Server Anywhere databases and all UltraLite applications
on platforms other than Windows CE use the character set determined
by the collating sequence of the database.
When you synchronize a remote database, the MobiLink
synchronization server performs character set translations between the
character set of the remote database and Unicode.

49
Character-set considerations

Character-set translation during synchronization: non-Windows


ODBC drivers on non-Windows platforms do not have Unicode entry points.
The MobiLink synchronization server exchanges data with the ODBC driver
using the character set determined by the collating sequence of the remote
database.
When the remote database is an UltraLite applications running under
Windows CE, the MobiLink synchronization server performs character-set
translation between Unicode and the character set being used with ODBC.

Controlling ODBC driver character-set translation


Because most consolidated databases are unlikely to use Unicode, it is
important to understand how the ODBC driver for your consolidated
database system converts data to and from Unicode. Some ODBC drivers use
the language settings of the machine running MobiLink to determine what
character set to use. In these cases, it is best if the language and code-page
settings of the machine running the MobiLink synchronization server match
those of the consolidated database.
Other ODBC drivers, such as the driver for Sybase Adaptive Server
Enterprise, allow each connection to use a specific character set. To avoid
translation errors, the character set used by MobiLink should be set to match
that of the consolidated database.
$ For a detailed description of how character-set translations take place in
your database server’s ODBC driver, consult that product’s ODBC driver
documentation.

50
Chapter 3 Synchronization Basics

Transport-layer security
Often, communication between a remote site and a MobiLink
synchronization server must take place over a public network or via wireless
communication. Ordinarily, the data contained in the upload and download
streams is susceptible to unauthorized access. For example, someone with a
suitable radio or network connection could listen to your communication or
intercept it.
MobiLink incorporates Certicom encryption technology, giving you the
option of encrypting your transmissions so that you can maintain secrecy and
security when synchronizing over an insecure network.
Invoking transport- You can use transport-layer security when using the TCP/IP or HTTP
layer security communication protocol. To invoke security, use the security parameter
when specifying your communication protocol. Set the security to the cipher
suite of your choice.
At present, the only cipher suite available is Certicom TLS. You may license
a version of the cipher suite that uses 56-bit encryption, or one that uses
128-bit encryption, subject to export restrictions. A client using 56-bit
encryption can communicate with a MobiLink synchronization server
equipped with the 128-bit cipher, but not vice versa.
Transport-layer security is separately licensed from SQL Anywhere Studio.
Please contact Sybase for further information.
Example ♦ Starting the MobiLink synchronization server as follows allows
connections through TCP/IP. All communication through this
connection will be encrypted using the Certicom cipher suite
dbmlsrv7 -x tcpip{port=3333;security=certicom_tls} ...

How transport- Transport-layer security works by filtering all in-going and all out-going
layer security communication through the cipher of your choice. The translation occurs
works between the MobiLink synchronization server and the communication
protocol of your choice. For example, adding security to a TCP/IP
connection affects the architecture as shown in the following diagram.

51
Transport-layer security

No security Certicom TLS security

database database
server server

MobiLink MobiLink
synchronization synchronization
server server

Certicom
TCP/IP TCP/IP
TLS

connections with connections with


remote sites remote sites

The only cipher currently supported is Certicom elliptic-curve encryption. To


specify this cipher, include the communication parameter
security=certicom_tls when you start the MobiLink synchronization server.
Transportation-level security requires additional communication between a
MobiLink client and the MobiLink synchronization server before the upload
stream is sent. When a client initiates synchronization, it passes a message to
the server. The client encrypts this message using the server’s public key.
The server, decrypts this message using its private key. Initially, the server
encrypts all messages to the client using the client’s public key.
While this public-key/private-key cipher is secure, as long as the private keys
are kept secret, the encryption and decryption process is computationally
intensive. To make further communication more efficient, the client and
server agree upon and exchange another key and switch to a symmetric key
cipher. They use this key and cipher for the rest of their communication
because the symmetric cipher allows data to be encrypted and decrypted
more efficiently.

52
Chapter 3 Synchronization Basics

Server authentication
One possible method of breaking a system of this type is to masquerade as
the server. The client connects to what it thinks is the server, but the
connection is unknowingly made to another, hostile server. To guard against
this form of attack, the server must use authentication certificates. The
client can safely assume the server is the correct one as long as the certificate
itself is guarded carefully.
The Certicom security software built into MobiLink uses certificates for the
purpose of server identification. A sample certificate is provided with
Adaptive Server Anywhere. The sample certificate is called mobilink.crt.
The password for the sample certificate is tJ1#m6+W.

Caution
The sample certificate should be used for testing purposes only. The
sample certificate provides no security in deployed situations because it
and the corresponding password are widely distributed with Sybase
software. To protect your system, you must create your own certificate.

Invoking server You invoke server authentication by specifying the following parameters to
authentication the security cipher. The following parameters are required when using a
certificate other than the sample certificate.
♦ certificate The file name of the certificate. The MobiLink
synchronization server searches for this file in the same way that it
locates executable files. It searches the directories in your path, the
directory in which the MobiLink synchronization server executable
resides, and your current directory. The default value is mobilink.crt.
♦ certificate_password The password for the certificate named above.
The default value is tJ1#m6+W.

Example Starting the MobiLink synchronization server as follows allows connections


through TCP/IP. All communication through this connection will be
encrypted using the Certicom cipher suite and clients can verify server
identity using the sample certificate. This command should be entered on a
single line.
dbmlsrv7 -x tcpip{port=2439;
security=certicom_tls{certificate=mobilink.crt;
certificate_password=tJ1#m6+W}} ...

Obtaining The sample certificate is for testing purposes only. It provides no security
certificates of because the certificate and password are distributed with Sybase software.
authentication You must obtain a customized certificate from Certicom to create or deploy
your own secure system.

53
Transport-layer security

Client architecture
To synchronize with a MobiLink synchronization server through secure
means, the client must use the same cipher suite as the server. All messages
received from the server via a communication protocol, such as TCP/IP, are
decrypted before being passed to the remote MobiLink client. The following
diagram depicts how Certicom TLS cipher suite is added to a client using
TCP/IP to communicate with a MobiLink synchronization server.

No security Certicom TLS security

connection to MobiLink connection to MobiLink


synchronization server synchronization server

TCP/IP TCP/IP
Certicom
TLS

UltraLite UltraLite
application application
or or
Adaptive Server Adaptive Server
Anywhere client Anywhere client

Adaptive Server Anywhere clients


To invoke transport-layer security when using an Adaptive Server Anywhere
client, you set the security parameter in the ADDRESS field of a
synchronization definition. Similarly, you can specify the parameter in the
ADDRESS field of a synchronization template or site, then extract the
database. The corresponding synchronization definition in the extracted site
inherits the security parameter and value.
Example ♦ The address clause of the following synchronization definition specifies
that the connection to myhost should be made using the Certicom TLS
cipher suite.
CREATE SYNCHRONIZATION DEFINITION mysharedtables
SITE ’demo_sync_site’
TYPE ’tcpip’
ADDRESS ’host=myhost;security=certicom_tls’
OPTION memory=2m,dir=c:\db\logs
(table People( person_id, fname, lname ),
table Pets WHERE pet_id=2);

54
Chapter 3 Synchronization Basics

UltraLite clients
To invoke transport-layer security when using an UltraLite client, you must
set specific parameters before initiating synchronization. For example, when
coding in C, you would ordinarily call the ULSynchronize function to
trigger synchronization with the consolidated database through a MobiLink
synchronization server.
When you build your application, the UltraLite analyzer recognizes the new
parameters and automatically builds all the necessary encryption components
into your UltraLite application.
$ For detailed information about synchronizing UltraLite applications,
see "Adding synchronization to your application" on page 74 of the book
UltraLite Developer’s Guide.

Obtaining MobileTrust server-authentification certificates


Certicom’s MobileTrust™ service provides e-commerce server
authentification certificates for server administrators to use with MobiLink
synchronization. These certificates are trusted by MobiLink clients that
include the Certicom root certificate.
$ For Detailed information about pricing, availability, policies, and
procedures are available at http://www.certicom.com/mobiletrust/.
Detailed instructions are available at the above site, but the general
procedure for obtaining and testing a MobileTrust server certificate is
as follows.
1 On your server, generate an ECDSA key pair and certificate request with
the application reqtool, provided with SQL Anywhere. Save these files
as indicated in the detailed instructions.
$ For detailed information about the reqtool utility, see the file
reqtool.pdf, located in the win32 directory of your SQL Anywhere
installation.
2 Read the agreement and policies document located on the web at
http://www.certicom.com/mobiletrust/ecommerceserver/. Latest pricing
and payment instructions are provided on the web site. Payment or
promise of payment, as well as consent to the terms and conditions of
the agreement, are required before Certicom issues your certificate.
3 Fill out the web form as completely as possible. Copy the PKCS10
request from the request file and paste it into the web form.
4 Submit the web form.

55
Transport-layer security

5 Upon receipt, your request is processed by a MobileTrust Registration


agent. Once processing is complete, you are supplied with a password
with which to retrieve your server certificate from the MobileTrust web
site.
6 Save the new certificate file on the machine that runs the MobiLink
synchronization server.
7 Start the MobiLink synchronization server, specifying the certificate file
name and password using the certificate and certificate_password
communication parameters.
The following statement starts the MobiLink synchronization server on
the TCP/IP port number 2439. In this example, the certificate chain and
private key are both stored in the file newcrt.crt.
dbmlsrv7 -x tcpip{port=2439;
security=certicom_tls{certificate=C:\newcrt.crt;
certificate_password=tJ1#m6+W}} ...
8 Test the certificate installation with an appropriately configured
MobiLink client.

56
C H A P T E R 4

Writing Synchronization Scripts

About this chapter You control the synchronization process by writing synchronization scripts
and storing them in the consolidated database. This chapter describes the role
these scripts play and how to write them.
Contents
Topic Page
Introduction to synchronization scripts 58
Scripts and the synchronization process 62
Script versions 67
Adding scripts to your consolidated database 68
Writing scripts to download rows 72
Writing scripts to upload rows 77
Writing scripts to handle errors 81
DBMS-dependent scripts 84

57
Introduction to synchronization scripts

Introduction to synchronization scripts


Synchronization scripts consist of SQL statements stored in your
consolidated database. During synchronization, the MobiLink
synchronization server reads the scripts and executes them against the
consolidated database. Scripts provide you opportunities to perform tasks at
various points of time during the synchronization process. You can use
Sybase Central to add scripts to the consolidated database.
The synchronization process is composed of multiple steps. A unique event
name identifies each step. You control the synchronization process by
writing scripts associated with some of these events. You write a script only
when some particular action must occur at a particular event. The MobiLink
synchronization server executes each script when its associated event occurs.
If you do not define a script for a particular event, the MobiLink
synchronization server simply proceeds to the next step.
For example, one event is named begin_upload_rows. You can write a
script and associate it with this event. The MobiLink synchronization server
reads this script when it is first needed, and executes it during the upload
phase of synchronization. If you write no script, the MobiLink
synchronization server proceeds immediately to the next step, which is
processing the uploaded rows.
Some scripts, called table scripts, are associated not only with an event, but
also with a particular table in the remote database. The MobiLink
synchronization server performs some tasks on a table-by-table basis; for
example, downloading rows. You can have many scripts associated with the
same event, but each with different application tables. Alternatively, you can
define many scripts for some application tables, but none for others.
$ For an overview of the synchronization steps, see "Steps in the
synchronization process" on page 33.

A simple synchronization script


MobiLink provides many events that you can exploit, but it is not mandatory
to provide scripts for each event. In a simple synchronization model, you
may need only a few scripts.
The ULProduct table in the CustDB sample application is synchronized by
downloading all the rows from the table to each remote database. In this
case, no additions are permitted at the remote databases. You can implement
this simple form of synchronization with a single script; in this case only one
event has a script associated with it.

58
Chapter 4 Writing Synchronization Scripts

The MobiLink event controlling the rows to be downloaded during each


synchronization is named download_cursor. Cursor scripts must contain
SELECT statements. The MobiLink synchronization server uses these
queries to define a cursor. In the case of a download_cursor script, the
cursor selects the rows to be downloaded to one particular table in the remote
database.
In the CustDB sample application, there is a single download_cursor script
for the ULProduct table in the sample application, which consists of the
following query.
SELECT prod_id, price, prod_name
FROM ULProduct
This query generates a result set. The rows that make up this result set are
downloaded to the client. In this case, all the rows of the table are
downloaded.
The MobiLink synchronization server knows to send the rows to the
ULProduct application table because this script is associated with both the
download_cursor event and ULProduct table by the way it is stored in the
consolidated database. Sybase Central facilitates exist to allow you to make
these associations.

Note
In this example, the query selects data from a consolidated table also
named ULProduct. The names need not match. You could, instead,
download data to the ULProduct application table from any table, or any
combination of tables, in the consolidated database by rewriting the query.

You can write more complicated synchronization scripts. For example, you
could write a script that downloads only recently modified rows, or one that
provides different information to each remote database. These issues are the
subject of this and the following chapter.

Adding scripts to your consolidated database


You can write and modify synchronization scripts using Sybase Central.

v To add a script to a database


1 Start Sybase Central and connect to a database. In this case, use the
CustDB sample database.
♦ Select Manage MobiLink Synchronization from the Adaptive
Server Anywhere program group.

59
Introduction to synchronization scripts

$ For a description of how to carry out this step, see "Lesson 8:


Browse the consolidated database" on page 40 of the book UltraLite
Developer’s Guide.
2 Under the UltraLite Sample database icon, open the Synchronized
Tables folder. Then double-click the ULProduct table.
ULProduct has a single synchronization script, associated with the
download_cursor event. This is the script described in the previous
section.
3 You could add a new script to the ULProduct table by double-clicking
Add Table Script. A wizard is displayed.

If you were adding a script to the database, you would select an event
from the list, and enter the script text into the space provided. Do not do
this at this time.

Using this chapter


The first section of this chapter provides a introduction to the kinds of
MobiLink scripts available and how these scripts fit into the synchronization
process.
♦ For a description of the types of scripts that you can write, see "Script
types" on page 64.

60
Chapter 4 Writing Synchronization Scripts

♦ For a description of how scripts are associated with a sequence of events


that occur during the synchronization process, see "Scripts and the
synchronization process" on page 62.
Later sections describe the following topics:
♦ How to add scripts to your consolidated database ("Adding scripts to
your consolidated database" on page 59).
♦ Details of how the scripts that handle the data transfer work ("Writing
scripts to upload rows" on page 77, "Writing scripts to download rows"
on page 72).
♦ How to write a script to handle errors ("Writing scripts to handle errors"
on page 81).

61
Scripts and the synchronization process

Scripts and the synchronization process


Each script corresponds to a particular event in the synchronization process.
You write a script only when some action must occur at a particular event.
All unnecessary scripts can be left undefined.
The two principal parts of the process are the processing of uploaded
information and the preparation of rows for downloading. This section
describes the events that are available during synchronization and the order
in which they occur.
The MobiLink synchronization server reads and prepares each script once,
when it is first needed. The script is then executed whenever the event is
invoked.
Reading the Each event is listed in order. For example, begin_connection is the first
pseudo-code event that is invoked.
In the pseudo-code below, events are followed by the parameters that any
script associated with that event can accept. For example, the
begin_synchronization connection script receives a single parameter, which
is the user name that the application supplied in the synchronization call.
You can, optionally, use the values of these parameters within your scripts.
The sequence of The following pseudo code outlines the sequence in which events are
events invoked.
begin_connection
COMMIT
for each synchronization
begin_synchronization(user_name)
for each remote table
begin_synchronization(user_name, table)
next table
COMMIT

process upload stream (see separate diagram)


COMMIT

prepare download stream (see separate diagram)


COMMIT

for each remote table


end_synchronization(user_name, table)
next table

62
Chapter 4 Writing Synchronization Scripts

end_synchronization(user_name)
COMMIT
next synchronization
end_connection
COMMIT
$ For the details of upload stream processing, see "Script events during
upload" on page 78.
$ For the details of download stream processing, see "Events during
download" on page 76.
Notes ♦ MobiLink technology allows multiple clients to synchronize
concurrently. In this case, each client uses a separate connection to the
consolidated database.
♦ The begin_connection and end_connection events are independent of
any one synchronization, as one connection can handle many
synchronization requests. These scripts have no parameters. These are
examples of connection-level scripts.
♦ Some events are invoked only once for each synchronization and have a
single parameter. This parameter is the user name, which uniquely
identifies the MobiLink client that is synchronizing. These are also
examples of connection-level scripts.
♦ Some events are invoked once for each table being synchronized. Scripts
associated with these events are called table-level scripts. They provide
two parameters. The first is the user name supplied in the call to the
synchronization function, and the second is the name of the table in the
remote database being synchronized.
While each table can have its own table scripts, you can also write table-
level scripts that are shared by several tables.
♦ Some events, such as begin_synchronization, occur at both the
connection level and the table level. You can supply both connection
and table scripts for these events.
♦ The COMMIT statements illustrate how the synchronization process is
broken up into distinct transactions.
♦ Errors are a separate event that can occur at any point within the
synchronization process. Errors are handled using the following script.
handle_error(error_code, error_message, user_name,
table_name )
$ For reference material, including detailed information about each script
and its parameters, see "Reference" on page 149.

63
Scripts and the synchronization process

Script types
Synchronization scripts fall into the following categories.
♦ cursor scripts These scripts perform the actions associated with upload
and download of data. Each script is associated with one particular
remote table. These scripts are the first scripts to consider when learning
about synchronization.
♦ connection scripts These scripts perform actions that are connection-
specific or synchronization-specific and that are independent of any one
remote table. These scripts are used in conjunction with other scripts
when implementing more complex synchronization schemes.
♦ table scripts These scripts perform actions specific to one
synchronization and one particular remote table. These scripts are used
in conjunction with other scripts when implementing more complex
synchronization schemes.

Cursor scripts
Each cursor script must contain a SELECT statement. The MobiLink
synchronization server defines a cursor based on this statement.
The following cursor script events are available. The first three are the ones
used most frequently.
♦ upload_cursor This script defines a cursor through which the
MobiLink synchronization server applies the upload stream to the
consolidated database, during the first step of synchronization.
$ For information, see "Writing scripts to upload rows" on page 77.
♦ download_cursor This script prepares inserts and updates for
download to remote databases during the second step of
synchronization. You must define a download_cursor cursor script for
each remote table to which you want to download rows.
$ For information, see "Writing scripts to download rows" on
page 72.
♦ download_delete_cursor This script prepares deletes for download to
remote databases during the second step of synchronization. You use
this script to select rows that are to be deleted from the remote database.
$ For information, see "Deleting rows with the
download_delete_cursor script" on page 74.

64
Chapter 4 Writing Synchronization Scripts

The following cursor script events are also available. These scripts are used
for conflict resolution.
♦ old_row_cursor Defines a cursor that the MobiLink synchronization
server uses to insert the old values of uploaded rows.
♦ new_row_cursor Defines a cursor that the MobiLink synchronization
server uses to insert the new values of uploaded rows.
$ For information, see "Handling conflicts" on page 109.

Connection scripts
Connection scripts control actions centered on connecting, and
disconnecting. They also permit actions at synchronization-level events such
as beginning and ending the upload or download process.
You only need to write a connection-level script when some action must
occur at a particular event. You may need to create scripts for only a few
events. The default action at any event is for the MobiLink synchronization
server to carry out no actions. Some simple synchronization schemes need no
connection scripts.

Table scripts
Table scripts allow actions at specific events relating to the synchronization
of a specific table, such as the start or end of uploading rows, resolving
conflicts, or selecting rows to download.

Script parameters
Most synchronization scripts receive parameters from the MobiLink
synchronization server. You can use these parameters in your scripts by
placing question marks in the script.
The following parameters are typically available within scripts.
♦ synchronization user name The value of this parameter is the string
that uniquely identifies a MobiLink client. Each client must identify
itself by this name when initiating synchronization with a MobiLink
synchronization server. This parameter is available within most
connection-level scripts, all table-level scripts, and some cursor scripts.
The user name can be used to partition tables among remote databases.

65
Scripts and the synchronization process

♦ table name This parameter identifies a table in the remote database.


The consolidated database may or may not contain a table with the same
name. Only table scripts use this parameter.
To use parameters, place a single question mark in your script for each
parameter. Some parameters are optional. The MobiLink synchronization
server replaces each question mark with the value of a parameter. It
substitutes values in the order the parameters appear in the script definition.
Upload scripts are The upload_cursor script, which is used to process the upload stream, is an
exceptions exception to the rule. The parameters to this script are the values of the
columns of the primary key in the remote database. These parameters are
ordered in the same order as the corresponding columns are defined in the
reference database. The MobiLink synchronization server requires these
parameters to update, delete, or select rows in the consolidated database. You
must use all parameters in a WHERE clause so as to uniquely identify a row
in the consolidated database.
The old_row_cursor and new_row_cursor scripts use no parameters
because they are used only to insert rows.
$ For the specific parameters available to each script, see "Scripts" on
page 173.

Table names need not match


The names of tables in the remote databases need not match the names of the
tables in the consolidated database. The MobiLink synchronization server
determines which scripts are associated with a table by looking up the remote
table name in the ml_table table.
The synchronization scripts for a given table can refer to any table, or
combination of tables, in the consolidated database. You can use this feature
to fill a particular remote table with data stored in one or more consolidated
tables, or to store data uploaded from a single remote table into multiple
tables in the consolidated database.

66
Chapter 4 Writing Synchronization Scripts

Script versions
Scripts are organized into groups called script versions. By specifying a
particular version, MobiLink clients can select which set of synchronization
scripts will be used to process the upload stream and prepare the download
stream.
Application of Script versions allow you to organize your scripts into sets, which are run
script versions under different circumstances. This ability provides flexibility and is
especially useful in the following circumstances.
♦ customization Using a different set of scripts to process information
from different types of remote users. For example, you could write a
different set of scripts for use when managers synchronize their
databases than would be used for other people in the organization.
Although you could achieve the same functionality with one set of
scripts, these scripts would be more complicated.
♦ upgrading applications When you wish to upgrade a database
application, new scripts may be needed because the new version of your
application may handle data differently. New scripts are almost always
necessary when the remote database changes. It is usually impossible to
upgrade all users simultaneously. MobiLink clients can request that a
new set of scripts be used during synchronization. Since both old and
new scripts can coexist on the server, all users can synchronize, no
matter which version of your application they are using.
♦ multiple applications A single MobiLink synchronization server may
need to synchronize two entirely different applications. For example,
some employees may use a sales application, whereas others require an
application designed for inventory control. When two applications
require different sets of data, you can create two versions of the
synchronization scripts, one version for each application.

Assigning version A script version name is a string. You specify this name when you add a
names script to the consolidated database. For example, if you add your scripts with
the ml_add_connection_script and the ml_add_table_script stored procedures,
the script version name is the first parameter. Alternatively, if you add your
scripts using Sybase Central, you are prompted for the version name.
The default script Whenever a remote site fails to supply a script version, the MobiLink
version synchronization server uses the first version defined in the ml_script_version
table.

67
Adding scripts to your consolidated database

Adding scripts to your consolidated database


When you set up a non-Adaptive Server Anywhere consolidated database for
use with MobiLink, you run a script that creates a set of MobiLink system
tables. The tables are created automatically when you create an Adaptive
Server Anywhere database.
The MobiLink system tables hold information about which tables are
involved in synchronization, about the user names involved in
synchronization, and about the synchronization scripts.
$ For information about the MobiLink system tables, see "MobiLink
system tables" on page 36.

Sybase Central is the synchronization management tool


Sybase Central provides an environment for managing synchronization. You
can add new scripts, edit existing ones, and even test your scripts against
your consolidated database.
$ For a description of how to add scripts to a consolidated database using
Sybase Central, see "Adding scripts to your consolidated database" on
page 59.
This section describes other ways of adding scripts that you may wish to use
if you work in a more automated environment.
$ For a description of the MobiLink system tables, see "Creating a
consolidated database" on page 38.

Using stored procedures to add synchronization scripts


You can add scripts to a database using stored procedures that are installed
along with the MobiLink system tables when you create a consolidated
database. The CustDB sample application uses these stored procedures.

Adaptive Server Enterprise limitation


You cannot use stored procedures to add scripts longer than 255 bytes to
Adaptive Server Enterprise. Instead, use Sybase Central or direct insertion
to define longer scripts.

68
Chapter 4 Writing Synchronization Scripts

Adding connection You use the ml_add_connection_script procedure to add a connection script.
scripts For example, the following statement adds a connection script associated
with the begin_synchronization event. The script itself is the single
statement that sets the @EmployeeID variable.
call ml_add_connection_script( ’custdb’,
’begin_synchronization’,
’set @EmployeeID = ?’ )
This example is taken from the file custdb.sql. It applies to Adaptive Server
Anywhere databases. Other consolidated databases may require a different
syntax.
Adding table and You use the ml_add_table_script procedure to add table and cursor scripts.
cursor scripts For example, the following command adds a cursor script associated with the
upload_cursor event on the ULCustomer table.
call ml_add_table_script( ’custdb’,
’ULCustomer’,
’upload_cursor’,
’SELECT cust_id, cust_name
FROM ULCustomer WHERE cust_id = ?’ )

Quotes in scripts
If you add a script using a stored procedure, the script is a string. Any
strings within the script need to be escaped. For Adaptive Server
Anywhere, each quotation mark (’) needs to be doubled so as not to
terminate the string.

Direct inserts of scripts


The scripts are stored in the MobiLink system tables, and so you can
construct INSERT statements that directly add the script into the MobiLink
system tables.
The details of the INSERT statements can be seen in the source code for the
ml_add_connection_script and ml_add_table_script stored procedures. The
source code for these stored procedures is dependent on the DBMS you are
using as a consolidated database, and the different versions can be found in
the syncasa.sql, syncase.sql, syncmss.sql, syncdb2.sql, and syncora.sql
scripts.
The syncasa.sql script is held in the scripts subdirectory of your Adaptive
Server Anywhere installation directory. The other scripts are held in the
MobiLink\setup subdirectory. IBM DB2 only supports column names and
other identifiers of 18 characters or less, and so the names are truncated. For
example, ml_add_connection_script is shortened to ml_add_connection_.

69
Adding scripts to your consolidated database

Example scripts for UltraLite


When you build an UltraLite application, the UltraLite generator
automatically inserts a example_upload_cursor script and a
example_download_cursor script into the UltraLite reference database.
The action of the example download script is to download all rows of a
corresponding table that exists in the remote database. These scripts specify
the select list in the correct order and the example upload_cursor script
includes the correct WHERE clause.
The example scripts are inserted into the ml_scripts table, but they are not
used unless you insert an entry in the ml_table_script table that associates
them with the upload_cursor or download_cursor event, respectively.
Minimally, the example scripts for download cursors provide the order of
columns expected by the remote database.
$ For information on adding the MobiLink system tables to your
reference database, see "Creating a consolidated database" on page 38.

Testing script syntax


As you develop your synchronization scripts, you can use Sybase Central to
test for syntax errors in your scripts.
Testing the scripts is done without any remote site in place. No data is added
to the database or downloaded from the database during testing. The validity
of the synchronized data itself is not tested.

v To test a your synchronization scripts


1 Start Sybase Central and connect to a database. In this case, use the
CustDB sample database.
♦ Select Manage MobiLink Synchronization from the Sybase
program group.
$ For a description of how to carry out this step, see "Lesson 8:
Browse the consolidated database" on page 40 of the book UltraLite
Developer’s Guide.
2 Under the UltraLite Sample database icon, right click on the
Synchronized Tables folder or the Connection scripts folder, and select
Test Scripts from the popup menu. The script-testing window is
displayed.

70
Chapter 4 Writing Synchronization Scripts

3 Click Test. If prompted, choose to use the default user name. The results
of the test are displayed in the window.
The test results include a listing of which scripts are executed, in which
order. They also include a listing of any syntax errors or data type errors
found during the test.

71
Writing scripts to download rows

Writing scripts to download rows


There are two cursor scripts that can be used during download-stream
processing for each table. These are the download_cursor script, which
carries out inserts and updates, and the download_delete_cursor script,
which carries out deletes.
These scripts are either SELECT statements or calls to procedures that return
result sets. The MobiLink synchronization server downloads the result set of
the script to the remote database. The MobiLink client automatically inserts
or updates rows based on the download_cursor script result set, and deletes
rows based on the download_delete_cursor event.

Writing download_cursor scripts


You write download_cursor scripts to download information from the
consolidated database to your remote database. You must write one of these
scripts for each table in the remote database for which you want to download
changes. You can use other scripts to customize the download process, but
no others are necessary.
♦ Each download_cursor script must contain a SELECT statement or a
call to a procedure that contains a SELECT statement. The MobiLink
synchronization server uses this statement to define a cursor in the
consolidated database.
♦ The script must select all columns that correspond to the columns in the
corresponding table in the remote database. The columns in the
consolidated database can have different names than the corresponding
columns in the remote database, but they must be of compatible types.
♦ The columns must be selected in the order that the corresponding
columns are defined in the remote database. This order is identical to the
order of the columns in the reference database.

Examples ♦ The following script could serve as a download_cursor script for a


remote table that holds employee information. The MobiLink
synchronization server would use this SQL statement to define the
download cursor. This script downloads information about all the
employees.
SELECT emp_id, emp_fname, emp_lname
FROM employee

72
Chapter 4 Writing Synchronization Scripts

♦ The MobiLink synchronization server passes specific parameters to


some scripts. To use these parameters, you include a question mark in
your SQL statement. The MobiLink synchronization server substitutes
the value of the parameter before executing the statement against the
consolidated database. The following script downloads information
about the employees that report directly to the present user.
SELECT emp_id, emp_fname, emp_lname
FROM employee
WHERE manager_id = ?
In this example, the MobiLink synchronization server replaces the
question mark with the value of the parameter to the download_cursor
script, which is the name of the present user.

Notes ♦ Row values can be selected from a single table or from a join of multiple
tables.
♦ The script itself need not include the name of the remote table. The
remote table need not have the same name as the table in the
consolidated database. The name of the remote table is identified by an
entry in the ml_table table. In Sybase Central, the remote tables are listed
together with their scripts.
♦ The rows in the remote table must contain the values of emp_id,
emp_fname, and emp_lname. The remote columns must be in that order,
although they can have different names. The columns in the remote
database are in the same order as those in the reference database.

UltraLite tip
The example scripts list the columns in the order that they are defined
in the reference database. Inspect the example_download_cursor
and example_upload_cursor scripts to see the column order.

♦ All cursor scripts must select the columns in the same order as the
columns are defined in the remote database. Where column names or
table structure is different in the consolidated database, columns should
be selected in the correct order for the remote database, or equivalently,
the reference database. Columns are assigned to columns in the remote
database based on their order in the SELECT statement.
♦ When you build an UltraLite application, the UltraLite generator creates
a sample download script for each table in your UltraLite application. It
inserts these sample scripts into your reference database. The example
scripts assume that the consolidated database contains the same tables as
your application. You must modify the sample scripts if your
consolidated database differs in design, but these scripts provide a
starting point.

73
Writing scripts to download rows

Deleting rows with the download_delete_cursor script


You write download_delete_cursor scripts to delete rows from your remote
database. You must write one of these scripts for each table in the remote
database from which you want to delete rows during synchronization.
The MobiLink synchronization server deletes rows by selecting values from
the consolidated database and passing those values to the remote database. If
the values match those of a primary key in the remote database, then that row
is deleted. If the primary key values match no remote row, the values are
discarded. The MobiLink synchronization server executes the SELECT
statement against the consolidated database; the deletes are performed in the
remote database.
♦ Each download_delete_cursor script must contain a SELECT
statement or a call to a stored procedure that returns a result set. The
MobiLink synchronization server uses this statement to define a cursor
in the consolidated database.
♦ This statement must select all the columns that correspond to the
primary-key columns in the table in the remote database. The columns in
the consolidated database can have different names than the
corresponding columns in the remote database, but they must be of
compatible types.
♦ The values must be selected in the same order as the corresponding
columns are defined in the reference database. That order is the order of
the columns in the CREATE TABLE statement used to make the table,
not the order they appear in the statement which defines the primary
key.
♦ The columns must be selected in the order that the corresponding
columns are defined in the remote database. This order is identical to the
order of the columns in the reference database.

Note
Each download_delete_cursor script must select all the column values
present in the primary key of the corresponding remote table. However, it
may, optionally, select all the other columns, too. This feature is present
only for compatibility with older clients. Selecting the additional columns
is less efficient, as the database engine must retrieve more data. Unless the
client is of an old design, the MobiLink synchronization server discards
the extra values immediately. The extra values are downloaded only to
older clients.

74
Chapter 4 Writing Synchronization Scripts

Examples ♦ The following selection could serve as a download_delete_cursor script


for a remote table that holds employee information. The MobiLink
synchronization server would use this SQL statement to define the delete
cursor. This script deletes information about all the employees.
SELECT emp_id
FROM employee
♦ The MobiLink synchronization server substitutes the value of the
parameter for question marks. The following script deletes information
about the employees that do not report directly to the present user.
SELECT emp_id
FROM employee
WHERE NOT manager_id = ?
In this example, the MobiLink synchronization server replaces the
question mark with the value of the parameter to the
download_delete_cursor script, which is the name of the present user.
♦ Optionally, the above example may be rewritten as follows, assuming
the remote table contains only these three columns. This format is
recommended only for use with older clients, as it is less efficient.
SELECT emp_id, emp_fname, emp_lname
FROM employee
WHERE NOT manager_id = ?

Tips
The above examples could prove inefficient in an organization with many
employees. You can make the delete process more efficient by selecting
only rows that could be present in the remote database. For example, you
could limit the number of rows by selecting only those people who have
recently been assigned a new manager.

Another strategy is to allow the client application to delete the rows itself.
This method is possible only when a rule identifies the unneeded rows.
For example, if the rows contain a timestamp that indicates an expiry date.
Use the STOP SYNCHRONIZATION DELETE statement to stop these
deletes being uploaded during the next synchronization.

$ You can use the referential integrity checking built into all MobiLink
clients to delete rows in a particularly efficient manner. For details, see
"Referential integrity and synchronization" on page 46.

75
Writing scripts to download rows

Events during download


The MobiLink synchronization server builds the download stream, in a
single transaction, as follows.
begin_download(user)
for each remote table
begin_download(user, table)
next table
for each remote table
begin_download_deletes(user, table)
SELECT using download_delete_cursor(user)
end_download_deletes(user, table)
begin_download_rows(user, table)
SELECT using download_cursor(user)
end_download_rows(user, table)
next table
for each remote table
end_download(user, table)
next table
end_download(user)
wait for confirmation from remote device or timeout
if ( confirmation ) then
COMMIT
else
ROLLBACK
end if

Notes ♦ Like the upload stream, the download stream starts and ends with
connection events. Other events are table-level events.
♦ If no confirmation of the downloads is received from the client, the
entire download transaction is rolled back in the consolidated database.
♦ The begin_download and end_download scripts for each remote table
hold logic that is independent of the individual rows being updated.
♦ The download stream does not distinguish between inserts and updates.
The script associated with the download_cursor event is a SELECT
statement that defines the rows to be downloaded. The client detects
whether the row exists or not and carries out the appropriate insert or
update operation.
♦ At the end of the download processing, the client automatically deletes
rows if necessary to avoid referential integrity violations.
$ For more information, see "Referential integrity and
synchronization" on page 46.

76
Chapter 4 Writing Synchronization Scripts

Writing scripts to upload rows


To upload information contained in your remote database to your
consolidated database, you must define an upload_cursor script. Each
upload_cursor script is specific to a particular table in the remote database.
The upload_cursor script is a SELECT statement that defines a cursor in the
consolidated database table. This cursor is used to apply uploaded inserts,
updates, and deletes. Although both upload_cursor and download_cursor
scripts contain queries, these queries perform different functions.

Writing upload_cursor scripts


The upload_cursor script takes a different set of parameters from other
scripts. This script takes one parameter for each column in the primary key
of the table. The script must be a SELECT statement. The WHERE clause of
the SELECT statement must use the parameters to uniquely identify rows in
the consolidated database.
For example, the ULCustomer upload_cursor script in the CustDB sample
application uses the primary key value of the ULCustomer table as a
parameter.
SELECT cust_id, cust_name
FROM ULCustomer
WHERE cust_id = ?

Meaning of the Although both upload_cursor and download_cursor scripts contain


SELECT statement SELECT statements, the meaning of the two statements is quite different.
The download script selects all rows to be downloaded, but the MobiLink
synchronization server requires the WHERE clause of the query in the
upload_cursor script to identify exactly one row in the consolidated
database to be updated or deleted.
Inserts are a If a table is to have only inserts at all remote databases, with no updates or
special case deletes, no WHERE clause is required. No rows are being deleted or
updated, and so the WHERE clause does not need to uniquely identify the
row.
The old_row_cursor and new_row_cursor scripts are always used only for
inserts. Therefore, they never require parameters or a WHERE clause.
SELECT FOR SELECT statements in the upload_cursor script define cursors through
UPDATE which updates, deletes, and inserts are performed. SELECT statements in the
new_row_cursor or old_row_cursor scripts are used in conflict resolution
define cursors through which inserts are performed.

77
Writing scripts to upload rows

Some database-management systems use an additional clause on the


SELECT statement to indicate that the query defines a cursor that may be
used for changes. If the DBMS you are using as a consolidated database uses
such a clause, you may wish to include it in SELECT statements in your
upload cursors.
Microsoft SQL Server, Sybase Adaptive Server Enterprise, IBM DB2, and
Oracle use a FOR UPDATE clause to indicate queries that may be updated.
No additional clause is required for Adaptive Server Anywhere.
Example The following upload_cursor script includes a WHERE clause, and the
condition in that clause uses the script parameters to uniquely identify a row
in the employee table.
SELECT emp_id, emp_fname, emp_lname
FROM employee
WHERE emp_id = ?
This example assumes that the employee ID number is the primary key of the
employee table in the consolidated database and, thus, uniquely identifies an
employee. This example also assumes that the remote table uses the
employee number as a primary key. The table and the employee number
column can have different names in the remote database as long as the
number, order, and type of columns in the SELECT statement correspond to
the number, order, and type of columns in the remote table.
The primary key, in this case the single column emp_id, is present in both
the list of selected columns and the WHERE clause. All columns in the
primary key of the remote table must be present in both positions.

Script events during upload


The MobiLink synchronization server processes the uploaded data, in a
single transaction, as follows.
begin_upload(user)
for each remote table
begin_upload(user, table)
next table
for each remote table
begin_upload_rows(user, table)

78
Chapter 4 Writing Synchronization Scripts

for each row uploaded from this table


if ( INSERT ) then
if ( upload_cursor defined ) then
INSERT using upload_cursor(pk1, …, pkn)
else
INSERT using new_row_cursor(pk1, …, pkn)
resolve_conflict(user, table)
end if
else if ( UPDATE ) then
if ( upload_cursor defined ) then
SELECT using upload_cursor(pk1, ..., pkn)
if ( not conflict ) then
UPDATE using upload_cursor(pk1, …, pkn)
end if
end if
if ( conflict or not upload_cursor defined )
INSERT using old_row_cursor(pk1, …, pkn)
INSERT using new_row_cursor(pk1, …, pkn)
resolve_conflict(user, table)
end if
end if
next row
end_upload_rows(user, table)
next table
for each remote table [reverse order]
begin_upload_deletes(user, table)
if ( DELETE ) then
for each row uploaded from this table
if ( upload_cursor defined ) then
DELETE using upload_cursor(pk1, …, pkn)
else
INSERT using old_row_cursor(pk1, …, pkn)
resolve_conflict(user, table)
end if
next row
end if
end_upload_deletes(user, table)
next table
for each remote table
end_upload(user, table)
next table
end_upload(user)
COMMIT

Notes ♦ The upload starts and ends with connection events. Other events are
table-level events.

79
Writing scripts to upload rows

♦ The begin_upload and end_upload scripts for each remote table hold
logic that is independent of the individual rows being updated.
♦ The MobiLink synchronization server uses the upload_cursor script to
fetch the values of existing rows from the consolidated database before
any updates are applied. These values are used to detect conflicts.
♦ The upload stream consists of single row inserts, updates, and deletes.
These are applied by opening a cursor on the appropriate tables and
applying the action through the cursor. The script associated with the
upload_cursor event is a SELECT statement that defines this cursor.
♦ The upload_cursor script takes a different set of parameters than the
other scripts. Its parameters are the primary key values identifying the
row being uploaded.

Conflict detection and resolution


When a row has been updated in the remote database, both old and new
values are sent during synchronization. If the row exists in the consolidated
database, the MobiLink synchronization server checks whether the values it
holds match the old values sent from the remote database. If the old values
match the current values, the MobiLink synchronization server updates the
row using new values sent from the remote database. If the old values do not
match the current values, a conflict is detected.

Caution
Never update primary keys in a MobiLink environment.

$ A conflict arises when the same row is updated in both the consolidated
and remote databases, independently. For more information about conflict
resolution, see "Handling conflicts" on page 109.

80
Chapter 4 Writing Synchronization Scripts

Writing scripts to handle errors


An error in a synchronization script occurs when an operation in the script
fails while the MobiLink synchronization server is executing it. The DBMS
returns a SQL Code to the MobiLink synchronization server indicating the
nature of the error. Each consolidated database DBMS has its own set of
SQL Codes.
When an error occurs, the MobiLink synchronization server invokes the
handle_error event. You should provide a connection script associated with
this event to handle errors. The MobiLink synchronization server passes
several parameters to this script to provide information on the nature and
context of the error, and requires an output value to tell it how to respond to
the error.
Error handling Some actions you may wish to take in an error-handling script are:
actions
♦ Log the error in a separate table.
♦ Instruct the MobiLink synchronization server whether to ignore the error
and continue, or rollback the synchronization, or rollback the
synchronization and shut down the MobiLink synchronization server.
♦ Send an e-mail message.

Parameters for error handling scripts


The MobiLink synchronization server passes the following parameters to the
handle_error script, which provide the nature of the error and the context in
which it occurred.
1 An integer holding the native SQL error code.
2 A string containing the error message from the DBMS.
3 A string holding the synchronization user name that requested this
synchronization.
4 A string holding the name of the table being referenced. If the offending
script was not a table script, then the table name is NULL.

Error handling scripts return an action code


The handle_error script consists of a call to a stored procedure. The stored
procedure must return an action code telling the MobiLink synchronization
server what to do next.

81
Writing scripts to handle errors

The action code is one of the following values:


♦ 1000 Skip the current row and continue processing.
♦ 3000 Rollback the current transaction and cancel the current
synchronization. This is the default action code, and is used when no
handle_error script is defined or this script causes an error.
♦ 4000 Rollback the current transaction, cancel the synchronization, and
shut down the server.
You can return a value from the handle_error script in two ways.
♦ Pass the action parameter to an OUTPUT parameter of a procedure:
CALL my_handle_error( ?, ?, ?, ?, ? )
♦ Set the action code via a procedure or function return value:
? = CALL my_handle_error( ?, ?, ?, ? )
Most DBMS’s use the RETURN statement to set the return value from a
procedure or function.
When the MobiLink synchronization server runs this script, it sets the action
code to a default value, depending on the type of error that occurred. Your
procedure may modify this code. In either case, however, your script must
return the action code.
The CustDB sample application contains error handlers for various database-
management systems.

Reporting errors
Since errors can disrupt the natural progression of the synchronization
process, it can be difficult to create a log of errors and their resolutions. The
report_error script provides a means of accomplishing this task. The
MobiLink synchronization server executes this script whenever an error
occurs. If the handle_error script is defined, it is executed immediately prior
to the reporting script.
The parameters to the report_error script are identical to those of the
handle_error script, except that the report_error script can not modify the
action code. Since the value of the action code is that returned by the
handle_error script, this script can be used to debug error-handling problems.
This script typically consists of an insert statement, which records the values,
perhaps with other data, such as the time or date, in a table for later
reference. To ensure that this data is not lost, the MobiLink synchronization
server always runs this script in a separate transaction and automatically
commits the changes as soon as this script completes.

82
Chapter 4 Writing Synchronization Scripts

Example The following report_error script, which consists of a single insert statement,
adds the script parameters into a table, along with the current date and time.
The script does not commit this change because the MobiLink
synchronization server always does so automatically.
INSERT INTO errors
VALUES( CURRENT DATE, ?, ? ,?, ?, ? );

Handling multiple errors on a single SQL statement


ODBC allows multiple errors per SQL statement, and some DBMSs make
use of this feature. Microsoft SQL Server, for example, can have two errors
for a single statement. The first is the actual error, and the second is usually
an informational message telling you why the current statement has been
terminated.
When a single SQL statement causes multiple errors, the handle_error
script is invoked once per error. The MobiLink synchronization server uses
the most severe action code (that is, the numerically greatest) to determine
the action to take. The same applies to the handle_error script.
If the handle_error script itself causes a SQL error, then the default action
code (3000) is assumed.

83
DBMS-dependent scripts

DBMS-dependent scripts
The MobiLink synchronization server can be used with ODBC compliant
databases other than Adaptive Server Anywhere, so some aspects of scripts
depend on the DBMS you are using.

Invoking procedures from scripts Some databases, SQL Server for


example, require that procedure calls with parameters be written using the
ODBC syntax.
{ CALL procedure_name( ?, ?, ... ) }
On these systems, an error-handler that uses a RETURN value can also be in
the following form. For example, you can return values in OUPUT
parameters in IBM DB2.
{ ? = CALL procedure_name( ?, ?, ... ) }

Adaptive Server Enterprise also requires the latter format when returning a
value from a procedure.

Numeric and decimal columns with ASE The current version of the
MobiLink synchronization server requires that primary key values of type
numeric or decimal be explicitly converted to their types under Adaptive
Server Enterprise.
You must add an explicit conversion to the numeric parameters in the script,
as shown in the following examples.
SELECT ...
WHERE numeric_col = CONVERT( NUMERIC, ? )
...
The above statement explicitly converts the first parameter to type
NUMERIC.
SELECT ...
WHERE decimal_col = CONVERT( DECIMAL(10,8), ? )
...
The above statement explicitly converts the first parameter to type
DECIMAL (10,8).

84
C H A P T E R 5

Synchronization Techniques

About this chapter This chapter describes a variety of techniques that you can use to tackle
common synchronization tasks encountered in MobiLink installations.
The techniques in this chapter are illustrated with examples taken from the
CustDB sample application.
Contents
Topic Page
Introduction 86
Development tips 88
The CustDB sample code 89
Synchronization performance tips 93
Snapshot synchronization 94
Timestamp-based synchronization 96
Partitioning rows among remote databases 101
Maintaining unique primary keys with primary-key pools 105
Handling conflicts 109
Miscellaneous techniques 113
Schema changes in remote databases 115

85
Introduction

Introduction
The previous chapter, "Writing Synchronization Scripts" on page 57,
describes how to write simple synchronization scripts, store them in your
database, and test that they are free of syntax errors.
Many useful synchronization features require not just one script, but a set of
scripts working together. This chapter describes how to implement some
common synchronization techniques.
Example The timestamp-based synchronization of the ULCustomer table used in the
CustDB sample application requires the following scripts:
♦ A begin_connection connection script to create a variable to hold the
last download time.
♦ A begin_download table script to maintain the last download time for
the current user in the consolidated database, and to assign a value to the
last download variable.
♦ An upload_cursor script on the ULCustomer table to apply changes
made at remote databases to the consolidated database.
♦ A download_cursor script on the ULCustomer table to download new
and updated rows to remote databases.

Some common techniques


The synchronization design in the CustDB sample application uses the
following features.
♦ Complete table downloads All rows and columns of the ULProduct
table are shared in their entirety with the remote databases.
♦ Column subsets All rows, but not all columns, of the ULCustomer
table are shared with remote databases.
♦ Row subsets Different remote users get different sets of rows from
the ULOrder table.
♦ Snapshot-based synchronization The ULProduct table is
synchronized using a simple method that downloads all rows each time
synchronization occurs.
$ For general information on this technique, see "Snapshot
synchronization" on page 94.

86
Chapter 5 Synchronization Techniques

♦ Timestamp-based synchronization A method of identifying changes


to the consolidated database made since the last time a device
synchronized. The ULCustomer and ULOrder tables are synchronized
using a method based on timestamps.
$ For general information on this technique, see "Timestamp-based
synchronization" on page 96.
♦ Primary key pools to maintain unique primary keys Ensuring that
primary-key values are unique across a complete MobiLink installation
is essential. The primary-key pool method used in this application is a
practical method for ensuring unique primary keys.
$ For general information on this technique, see "Maintaining unique
primary keys with primary-key pools" on page 105.

87
Development tips

Development tips
Adding synchronization functionality to an application adds an added level
of complexity to your application. The following tips may be useful.
♦ Wait If you try to add synchronization to a prototype application, it can
be difficult to deduce which functional components are causing
problems. This is particularly the case with UltraLite applications, where
database and application are compiled together. When developing a
prototype, temporarily hard code INSERT statements in your application
to provide data for testing and demonstration purposes. Once your
prototype is working correctly, enable synchronization and discard the
temporary INSERT statements.
♦ Go step-by-step Start with straightforward synchronization
techniques. Operations such as a simple upload or download require
only one or two scripts. Once those are working correctly, you can
introduce more advanced techniques, such as timestamps, primary-key
pools, and conflict resolution.
♦ Set a large server timeout value Many small devices have relatively
slow processors. When synchronizing through a serial connection, they
can take several minutes to process large download streams and return a
confirmation to the MobiLink synchronization server. To avoid timeout
error messages on the server when downloading large amounts of data,
specify a long timeout period when starting the MobiLink
synchronization server. This tip is particularly applicable to UltraLite
applications.
$ For MobiLink synchronization server parameters see, "MobiLink
synchronization server" on page 150.

88
Chapter 5 Synchronization Techniques

The CustDB sample code


The examples in this chapter are drawn from the CustDB sample application.
This UltraLite application is a MobiLink client. The application has been
designed to illustrate several common techniques. To get the most out of this
chapter, you should study the sample application as you read.
This section describes the pieces that make up the code for the sample
application and database. The sample code is held in the
UltraLite\samples\CustDB subdirectory of your SQL Anywhere installation
directory. Platform-specific user interface code is held in subdirectories
named for each operating system.

The CustDB sample database


The CustDB sample database is provided as an Adaptive Server Anywhere
database file. This database serves as a reference database, and as the
consolidated database.

Examples based on Adaptive Server Anywhere


The examples described here are based on Adaptive Server Anywhere
consolidated database. The SQL source code is held in the custdb.sql file.
Other files, such as custase.sql, custmss.sql, custora.sql, and custdb2.sql
files implement the same features in a way that is appropriate for other
databases.

In addition, SQL scripts are provided so that you can rebuild the sample
database or use a Sybase Adaptive Server Enterprise, Microsoft SQL Server,
Oracle, or IBM DB2 database as a consolidated database.
To prepare databases other than Adaptive Server Anywhere for use as
MobiLink consolidated databases, you must first run a script to install the
MobiLink system tables. These files, which have names such as syncase.sql,
syncmss.sql, syncora.sql, or syncdb2.sql, are located in the MobiLink\setup
subdirectory. You do not need to prepare Adaptive Server Anywhere
databases in this manner because the MobiLink system tables are
automatically added when you created the database.
The SQL scripts for the CustDB sample application perform the following
operations. On databases other than Adaptive Server Anywhere, these scripts
can be run only after the MobiLink system tables have been added.
♦ Create the CustDB tables The table definitions are included in the
scripts.
♦ Add the data The data for the CustDB database is added.
89
The CustDB sample code

♦ Add the synchronization scripts The synchronization scripts control


what happens when an application synchronizes. These scripts are added
to the database.

Creating a DB2 consolidated database for CustDB


The files needed to create a DB2 consolidate database for the CustDB
sample application are as follows:
♦ custdb2.sql
♦ custdb2.java and its compiled form, custdb2.class.
♦ custdb2setup.java and its compiled form, custdb2setup.class.
The custdb2.class file must be copied to the SQLLIB\FUNCTION directory
on the DB2 server machine. This file contains the implementations of the
procedures created in custdb2.sql.

v To set up a DB2 consolidated database for the sample application


1 Create a DB2 database on the DB2 server. Ensure that the default
tablespace (usually called USERSPACE1) uses 8 kb pages. You may
have to delete the default tablespace and re-create it with 8 kb pages.
Consult your DB2 documentation for more information.
2 If necessary, change the connect command in custdb2.sql.
3 Start a DB2 Command Window from either the server or client machine.
Enter the following command at the prompt:
db2 -c -ec -td~ +s -v -f custdb2.sql
4 When processing is complete, enter the following command to close the
command window.
exit

5 On the DB2 client machine, create an ODBC data source called CustDB
that references the DB2 database.
If you use a name other than CustDB, you will have to change the
connection code in custdb2setup.java and recompile it, as follows,
where jdk11dir is the path to your JDK 1.1 installation.
javac -g -classpath
jdk11dir\lib\classes.zip;%db2path%\java\db2java.zip;
%db2path%\java\runtime.zip custdb2setup.java

90
Chapter 5 Synchronization Techniques

6 Also on the client machine, run the custdb2setup Java application, as


follows, where username and password are the username and password
for connecting to the CustDB ODBC data source.
java custdb2setup [username password]

The custdb2setup.class file contains a Java application that resets the


CustDB example in the DB2 database. After the initial setup, you can run
this application at any time to reset the DB2 CustDB database.

Application logic source code


The application logic is held in the file custdb.sqc. This embedded SQL file
holds the SQL statements needed to query and modify information from the
UltraLite database and also holds the calls needed to start synchronization
with the consolidated database. The user-interface features are held
separately, in platform-specific subdirectories.

Synchronization logic source code


The source for the synchronization features of the sample application is the
custdb.sql file, with custase.sql, custmss.sql, custora.sql, and custdb2.sql
holding versions for other database-management systems. The scripts in
custdb.sql are included in the custdb.db Adaptive Server Anywhere database.

Inspecting the You can use Sybase Central to inspect the synchronization scripts in the
synchronization consolidated database.
scripts
$ For information on running Sybase Central, see "Lesson 8: Browse the
consolidated database" on page 40 of the book UltraLite Developer’s Guide.
Script types and The custdb.sql file adds each synchronization script into the consolidated
events database by calling ml_add_connection_script or ml_add_table_script.
Examples The following lines in custdb.sql add a connection-level script, which is
executed at the begin_connection event. The script consists of two CREATE
VARIABLE statements.
call ml_add_connection_script(
‘CustDB’,
'begin_connection',
'create variable @LastDownload timestamp;
create variable @EmployeeID integer;' )
go
The following lines add a table-level script for the ULProduct table, which is
executed at the download_cursor event. The script consists of a single
SELECT statement.

91
The CustDB sample code

call ml_add_table_script(
‘CustDB’,
'ULProduct', 'download_cursor',
'SELECT prod_id, price, prod_name FROM ULProduct' )
go
Some table-level scripts, such as this one, are associated with cursor events.
These scripts are primarily responsible for the movement of data. As they
play such a central role, this kind of table script is described separately as a
cursor script.
$ For more information about script types, see "Script types" on page 64.
$ For a listing of available script types and events, see "Reference" on
page 149.

92
Chapter 5 Synchronization Techniques

Synchronization performance tips


Synchronization performance can be addressed in several ways.
♦ Download only the rows you need The most important way to make
synchronization fast is to download only the rows that are required. It is
easier to write synchronization scripts that download all rows upon each
synchronization, but downloading unneeded rows can make the remote
database too large and also impacts synchronization performance.
♦ Communications speed If synchronization always occurs over a
LAN while the machine is docked, then communication will be
relatively fast. On the other hand, if synchronization may occur over a
phone line or other low-bandwidth link, then communication will not be
as fast and it is more important to have scripts that minimize the size of
the download stream.
♦ Optimize script execution The performance of your scripts in the
consolidated database is an important factor. It may help to create
indexes on your tables so that download_cursor scripts and
download_delete_cursor scripts can efficiently select the required
rows.
♦ Maximize concurrency Concurrency considerations in your scripts
can be an important factor for throughput.
For example, suppose a begin_download script increments a column in
a table to count the total number of downloads. If multiple users may
synchronize at the same time, this script would effectively serialize their
downloads. The same counter would be better in the
begin_synchronization or end_synchronization script because they are
called just before a commit.
$ For information on the transaction structure of synchronization, see
"Transactions in the synchronization process" on page 43.

93
Snapshot synchronization

Snapshot synchronization
Snapshot synchronization of a table is a complete download of all relevant
rows in the table at each synchronization, even if they have been downloaded
before. This is the simplest synchronization method, but can involve
unnecessarily large data sets being exchanged, which can limit performance.
You can use snapshot synchronization for downloading all the rows of the
table, or in conjunction with a partitioning of the rows as described in
"Partitioning rows among remote databases" on page 101.
When to use The snapshot method is typically most useful for tables that have both the
snapshot following characteristics.
synchronization
♦ Relatively few rows When there are few rows, the overhead
associated with downloading all of them is small.
♦ Rows that change frequently When most rows in a table change
frequently, there is little to be gained by explicitly excluding those that
have not changed since the last synchronization.
A table that holds a list of exchange rates could be suited to this approach
because there are relatively few currencies, but the rates of most change
frequently. Depending on the nature of the business, a table that holds prices,
a list of interest rates, or current news items could all be candidates.

v To implement snapshot-based synchronization


1 Leave the upload_cursor script undefined unless remote users update
the values.
2 If the table may have rows deleted, write a download_delete_cursor
script that deletes all the rows from the remote table, or at least all rows
no longer required. Do not delete the rows from the consolidated
database; rather, mark them for deletion. You must know the row values
to delete them from the remote database.
$ For more information, see "Deleting rows with the
download_delete_cursor script" on page 74.
3 Write a download_cursor script that selects all the rows you want to
include in the remote table.

Mark rows for deletion


Rather than deleting rows from the consolidated database, mark them for
deletion. You must know the row values to delete them from the remote
database. Select only unmarked rows in the download_cursor script and
only marked rows in the download_delete_cursor script

94
Chapter 5 Synchronization Techniques

The download_delete_cursor script is executed before the


download_cursor script. If a row is to be included in the download stream,
you need not include a row with the same primary key in the delete list.
When a downloaded row is received at the remote location, it replaces a
preexisting row with the same primary key.
$ For more information, see "Events during download" on page 76.
An alternate Rather than delete rows from the remote database using a download_cursor
deletion technique script, you can allow the remote application to delete the rows. For example,
immediately following synchronization, you could allow the application to
execute SQL statements that delete the unneeded rows.
Rows deleted by the application are ordinarily uploaded to the MobiLink
synchronization server upon the next synchronization, but you can prevent
this upload using the STOP SYNCHRONIZATION DELETE statement, as
follows.
STOP SYNCHRONIZATION DELETE;
DELETE FROM table-name
WHERE expiry_date < CURRENT TIMESTAMP;
COMMIT;
START SYNCHRONIZATION DELETE;
Naturally, a different condition may be required in the WHERE clause,
depending on the business logic of the application.
Example The ULProduct table in the sample application is maintained by snapshot
synchronization. The table contains relatively few rows, and for this reason,
there is little overhead in using snapshot synchronization.
1 There is no upload_cursor script. This reflects a business decision that
products cannot be added at remote databases.
2 There is no download_delete_cursor, reflecting an assumption that
products are not removed from the list.
3 The download_cursor script selects the product identifier, price, and
name of every current product. If the product is pre-existing, the price in
the remote table will be updated. If the product is new, a row will be
inserted in the remote table.
SELECT prod_id, price, prod_name
FROM ULProduct

95
Timestamp-based synchronization

Timestamp-based synchronization
The timestamp method is the most useful general technique for efficient
synchronization. The technique involves tracking the last time that each user
synchronized, and using this information to control the rows downloaded to
each remote database.
The information uploaded on synchronization is controlled automatically by
the client.

v To implement time-stamped synchronization for a single table


1 Add a column to the consolidated database to store the required date and
time information. In general, you will want to compare the last
download time for each user name with the last time each row was
modified. This column is not needed in the remote database.
2 For more convenient access create a connection-level variable to store
the last update time. Connection-level variables are specific to Adaptive
Server Anywhere.
In the CustDB example, this variable is named @LastDownload. The
variable is created during begin_connection, and set during
begin_download.
3 If applicable, write an upload_cursor script to upload changes from the
remote table.
4 Write a begin_download script that sets the variable to the previous
download time and records the current time as the last download time
for the next synchronization.
5 Use the previous download time in the download_deletes_cursor script
to control information deleted from the remote database.
6 Use the previous download time in the download_ cursor script to
control information downloaded to the remote database.
You can use an UPDATE trigger and an INSERT trigger at the consolidated
database to keep the last modification times current.

Timestamp synchronization example


The sample application uses timestamp-based synchronization for many of
its tables. Here, we look at timestamp synchronization of the ULCustomer
table.
In the consolidated database, ULCustomer has the following columns:

96
Chapter 5 Synchronization Techniques

♦ cust_id An integer primary key column.


♦ cust_name The customer name
♦ last_modified A timestamp column holding the last time the row was
modified. This column is excluded from the download_cursor script
because it does not appear in the remote database.
Timestamp-based synchronization requires that several scripts work together.
Each script is described in a separate section.

The begin_connection script


The begin_connection event takes place when the MobiLink
synchronization server connects to the consolidated database. As the
MobiLink synchronization server uses a connection pool, a single connection
may be shared by several synchronizing applications, one after another. The
begin_connection script is used for actions that are to be performed only
once per connection. Creating variables is an example of such an action.
This script creates two variables (@LastDownload and @EmployeeID),
which exist for the duration of the connection.
The script is as follows:
create variable @LastDownload timestamp;
create variable @EmployeeID integer;
Connection-level variables are available in Adaptive Server Anywhere, but
are generally unavailable in other databases. For Adaptive Server Enterprise
and Microsoft SQL Server, a temporary table is used. For Oracle, a global
session package is used.
$ For information about connection-level begin_connection scripts, see
"begin_connection connection script" on page 173.

The begin_synchronization script


The begin_synchronization event is triggered each time a client connects to
the MobiLink synchronization server to synchronize. A single parameter is
supplied to the begin_synchronization script, which is the user name of the
connecting user as supplied in the client synchronization call.
The script is as follows:
set @EmployeeID = ?
The value of the Employee ID is specific to the remote database that is
synchronizing, and so this value cannot be assigned in a begin_connection
script.

97
Timestamp-based synchronization

$ For more information about connection-level begin_synchronization


scripts, see "begin_synchronization connection script" on page 175.

The upload_cursor script


The first step in synchronization is to upload any changes made at the remote
database. The client automatically flags any rows changed since the last
successful synchronization, and all these flagged changes are sent to the
MobiLink synchronization server to be applied to the consolidated database.
The upload_cursor script defines a cursor through which these changes are
applied.
You do not need to implement timestamp synchronization logic for uploads.
The technique is applied only to the download phase.
The upload_cursor script is as follows.
SELECT cust_id, cust_name
FROM ULCustomer
WHERE cust_id = ?
The upload_cursor script takes a parameter value for each primary-key
column. In this case, the cust_id column is the single primary-key column for
the table.
For each row that has been updated, deleted, or inserted at the remote
database, the upload_cursor script is executed at the consolidated database.
The script opens a cursor on the ULCustomer table on the consolidated
database, positioned at the primary key specified in the operation.
If the operation is an INSERT, the cursor position is irrelevant. If the
operation is an UPDATE or DELETE, the cursor is positioned at the row,
and the row is updated or deleted.
$ For more information on upload_cursor scripts, see "upload_cursor
cursor script" on page 188.

The begin_download connection script


The begin_download event is invoked each time the MobiLink
synchronization server starts the download step of transferring data to the
remote database.
The connection-level begin_download script does not transfer data: cursor
scripts carry out that function. Instead, this script maintains the information
concerning the last time that synchronization occurred.
The Adaptive Server Anywhere version of this script is as follows.

98
Chapter 5 Synchronization Techniques

begin
set @LastDownload =
(select last_download from ULEmployee
where emp_id = @EmployeeID);
if @LastDownload is null then
set @LastDownload = years(CURRENT TIMESTAMP, -100);
end if;

update ULEmployee
set last_download = CURRENT TIMESTAMP
where emp_id = @EmployeeID;
end
The ULEmployee table is used to hold the last download time of each user
name. This table does not exist at the remote database. The script sets the
@LastDownload variable to the current value from the ULEmployee table,
and then updates the value in the table with the current time, ready for the
next synchronization. As the download takes place in a single transaction,
this change is rolled back if the download fails for any reason.
If this is the first download, then @LastDownload is set to a date that is
sufficiently long ago that all data is downloaded on the first attempt. In this
case, 100 years ago is chosen.
$ For more information on the steps involved in synchronization, see
"The synchronization process" on page 32.

The download_cursor script


The download_cursor script manages downloads of new or changed data to
the remote database. The query in this cursor defines which rows are to be
synchronized.

Upload and download cursor queries have different meanings


Despite their similar appearance, the upload_cursor and
download_cursor scripts operate in different ways. The rows to be
downloaded are defined by the download_cursor script. The rows to be
uploaded are defined by UltraLite itself, automatically; the
upload_cursor script defines the cursor through which these changes are
applied to the consolidated database.

The download_cursor script is as follows:


SELECT cust_id, cust_name
FROM ULCustomer
WHERE last_modified > @LastDownload
The script selects all rows changed since the last download.

99
Timestamp-based synchronization

In the sample application, there is no facility for deleting customers, and


hence no download_delete_cursor.
$ For more information on download_cursor scripts, see
"download_cursor cursor script" on page 177.

100
Chapter 5 Synchronization Techniques

Partitioning rows among remote databases


Each user of a MobiLink client database can contain a different subset of the
data in the consolidated database. Stated another way, you can write your
scripts so that data is partitioned among remote databases.
The partitioning may be disjoint, or it may contain overlaps. For example, if
each employee has their own set of customers, with no shared customers, the
partitioning would be disjoint. If there are shared customers, who appear in
more than one remote database, the partitioning contains overlaps.
Partitioning is implemented in the download_cursor and
download_delete_cursor scripts for the table, which define the rows to be
downloaded to the remote database. Each of these scripts has a single
parameter, which is the synchronization user name. By defining your scripts
using this parameter in the WHERE clause, each user gets the appropriate
rows.

Disjoint partitioning
Partitioning is controlled by the download_cursor and
download_delete_cursor scripts for each table involved in synchronization.
These scripts take a single parameter, which is the user name supplied in the
call to synchronize.

v To partition a table among remote databases


1 Include in the table definition a column containing the synchronization
user name in the consolidated database. You need not download this
column to remote databases.
2 Include a condition in the WHERE clause of the download_cursor and
downloade_delete_cursor scripts requiring this column to match the
script parameter.
The script parameter is represented by a question mark in the script. For
example, the following download_cursor script partitions a table
named Contact by employee ID.
SELECT id, contact_name
FROM Contact
WHERE emp_id = ?

Example The primary-key pool tables in the CustDB sample application are used to
supply each remote database with its own set of primary-key values. This
technique is used to avoid duplicate primary keys, and is discussed in
"Maintaining unique primary keys with primary-key pools" on page 105.

101
Partitioning rows among remote databases

A necessary feature of the method is that primary-key-pool tables must be


partitioned among remote databases in a disjoint fashion.
One key-pool table is ULCustomerIDPool, which holds primary-key values
for each user to use when they add customers. The table has three columns:
♦ pool_cust_id A primary key value for use in the ULCustomer table.
This is the only column downloaded to the remote database.
♦ pool_emp_id The employee who owns this primary key.
♦ last_modified This table is maintained using the timestamp
technique, based on the last_modified column.
$ For information on timestamp synchronization, see "Timestamp-
based synchronization" on page 96.
The download_cursor script for this table is as follows.
SELECT pool_cust_id
FROM ULCustomerIDPool
WHERE pool_emp_id = @EmployeeID
AND last_modified > @LastDownload
Instead of using the "?" placeholder, this script uses the @EmployeeID
variable to improve readability. The variable was set in the
begin_synchronization script to be the synchronization user name. When
not using a variable, you should use a join or sub-selection that includes the
"?" placeholder.

Partitioning with overlaps


Some tables in your consolidated database may have rows that belong to
many remote databases. Each remote database has a subset of the rows in the
consolidated database and the subset overlaps with other remote databases.
This is frequently the case with a customer table. In this case, there is a
many-to-many relationship between the table and the remote databases and
there will usually be a table to represent the relationship. The
download_cursor needs to join the table being downloaded to the
relationship table.
Example The CustDB sample application uses this technique for the ULOrder table.
The ULEmpCust table holds the many-to-many relationship information
between ULCustomer and ULEmployee.
Each client receives only those rows from the ULOrder table for which the
value of the emp_id column matches the user name supplied in the call to
ULSynchronize.

102
Chapter 5 Synchronization Techniques

The Adaptive Server Anywhere version of the download_cursor script for


ULOrder in the CustDB application is as follows:
SELECT o.order_id, o.cust_id, o.prod_id, o.emp_id,
o.disc, o.quant, o.notes, o.status
FROM ULOrder o , ULEmpCust ec
WHERE o.cust_id = ec.cust_id
AND ec.emp_id = @EmployeeID
AND ( o.last_modified > @LastDownload
OR ec.last_modified > @LastDownload)
AND ( o.status IS NULL
OR o.status != ’Approved’ )
AND ( ec.action IS NULL )
This script is fairly complex. It illustrates that the query defining a table in
the remote database can include more than one table in the consolidated
database. The script downloads all rows in ULOrder for which:
♦ the cust_id column in ULOrder matches the cust_id column in
ULEmpCust,
♦ the emp_id column in ULEmpCust matches the synchronization user
name,
♦ the last modification of either the order or the employee-customer
relationship was later than the most recent synchronization time for this
user,
♦ the status is anything other than Approved.
The action column on ULEmpCust is used to mark columns for delete. Its
purpose is not relevant to the current topic.
The download_delete_cursor script is as follows.
SELECT o.order_id
FROM ULOrder o, ULEmpCust ec
WHERE o.cust_id = ec.cust_id
AND ec.emp_id = @EmployeeID
AND ( o.last_modified > @LastDownload OR
c.last_modified > @LastDownload)
AND ( o.status IS NULL OR
o.status != ’Approved’ )
AND ( ec.action IS NULL )
This script deletes all approved rows from the remote database.

Partitioning child tables


The example above ("Partitioning with overlaps" on page 102) illustrates
how to partition tables based on a criterion in some other table.

103
Partitioning rows among remote databases

Some tables in your remote database may have disjoint subsets or


overlapping subsets, but do not contain a column that determines the subset.
These are child tables that usually have a foreign key (or a series of foreign
keys) referencing another table. The referenced table has a column that
determines the correct subset.
In this case, the download_cursor needs to join the referenced tables and
have a WHERE clause that restricts the rows to the correct subset.

104
Chapter 5 Synchronization Techniques

Maintaining unique primary keys with primary-


key pools
It is often convenient to use a single column as the primary key for tables.
For example, each customer should be assigned a unique identification value.
If all the sales representatives work in an environment where they can
maintain a direct connection to the database, assigning these numbers is
easily accomplished. Whenever a new customer is inserted into the customer
table, automatically add a new primary-key value that is greater than the last
value.
In a disconnected environment, assigning unique values for primary keys
when new rows are inserted is not as easy. When a sales representative adds
a new customer, she is doing so to a remote copy of the Customer table. You
must prevent other sales representatives, working on other copies of the
Customer table, from using the same customer identification value.
An UltraLite database is usually a small subset of the consolidated database.
For this reason, you cannot normally use automatically generated primary-
key values. Features that automatically generate primary-key values (like the
Adaptive Server Anywhere autoincrement feature or the Adaptive Server
Enterprise identity column) rely on having the entire table available.
One efficient means of solving this problem is to assign each user of the
database a pool of primary-key values to assign as the need arises. For
example, you can assign each sales representative 100 new identification
values. Each sales representative can freely assign values to new customers
from his own pool.

v To implement a primary-key pool


1 Add a new table to the consolidated database and to each remote
database to hold the new primary-key pool. Apart from a column for the
unique value, these tables should contain a column for a user name, to
identify who has been given the right to assign the value.
2 Write a stored procedure to ensure that each user is assigned enough
new identification values. Assign more new values to remote users who
insert many new entries or who synchronize infrequently.
3 Write a download_cursor script to select the new values assigned to
each user and download them to the remote database.
4 Modify the application that uses the remote database so that when a user
inserts a new row, the application uses one of the values from the pool.
The application must then delete that value from the pool so it is not
used a second time.

105
Maintaining unique primary keys with primary-key pools

5 Write an upload_cursor script. The MobiLink synchronization server


will then delete rows from the consolidated pool of values that a user has
deleted from his personal value pool in the remote database.
6 Write an end_upload script to call the stored procedure that maintains
the pool of values. Doing so has the effect of adding more values to the
user’s pool to replace those deleted during upload.

A primary-key pool example


The sample application allows remote users to add customers. It is essential
that each new row has a unique primary-key value, and yet each remote
database is disconnected when data entry is occurring.
The ULCustomerIDPool holds a list of primary-key values that can be used
by each remote database. In addition, the ULCustomerIDPool_maintain stored
procedure tops up the pool as values are used up. The maintenance
procedures are called by a table-level end_upload script, and the pools at
each remote database are maintained by upload_cursor and
download_cursor scripts.
1 The ULCustomerIDPool table in the consolidated database holds the pool
of new customer identification numbers. It has no direct link to the
ULCustomer table.

ULCustomer
cust_id integer
cust_name varchar(30)
last_modified timestamp

ULEmployee ULCustomerIDPool
emp_id = pool_emp_id
emp_id integer pool_cust_id integer
emp_name varchar(30) pool_emp_id integer
last_download timestamp last_modified timestamp

2 The ULCustomerIDPool_maintain procedure updates the


ULCustomerIDPool table in the consolidated database. The following
sample code is for an Adaptive Server Anywhere consolidated database.

106
Chapter 5 Synchronization Techniques

CREATE PROCEDURE ULCustomerIDPool_maintain ( IN


syncuser_id INTEGER )
BEGIN
DECLARE pool_count INTEGER;

-- Determine how may ids to add to the pool


SELECT COUNT(*) INTO pool_count
FROM ULCustomerIDPool
WHERE pool_emp_id = syncuser_id;

-- Top up the pool with new ids


WHILE pool_count < 20 LOOP
INSERT INTO ULCustomerIDPool ( pool_emp_id )
VALUES ( syncuser_id );
SET pool_count = pool_count + 1;
END LOOP;
END
This procedure counts the numbers presently assigned to the current
user, and inserts new rows so that this user has a sufficient supply of
customer identification numbers.
This procedure is called at the end of the upload stream, by the
end_upload table script for the ULCustomerIDPool table. The script is
as follows:
CALL ULCustomerIDPool_maintain( @EmployeeID )
3 The download_cursor script for the ULCustomerIDPool table
downloads new numbers to the remote database.
SELECT pool_cust_id
FROM ULCustomerIDPool
WHERE pool_emp_id = @EmployeeID
AND last_modified > @LastDownload
This script uses the @EmployeeID variable instead of the user name
placeholder, and uses timestamp replication to download only the
required rows.
4 To insert a new customer, the application using the remote database
must select an unused identification number from the pool, delete this
number from the pool, and insert the new customer information using
this identification number. The following embedded SQL function for an
UltraLite application retrieves a new customer number from the pool.

107
Maintaining unique primary keys with primary-key pools

bool CDemoDB::GetNextCustomerID( void )


/*************************************/
{
short ind;

EXEC SQL SELECT min( pool_cust_id )


INTO :m_CustID:ind FROM ULCustomerIDPool;
if( ind < 0 ) {
return false;
}
EXEC SQL DELETE FROM ULCustomerIDPool
WHERE pool_cust_id = :m_CustID;
return true;
}
5 The upload_cursor script deletes numbers from the consolidated pool
of numbers once they have been used and hence deleted from the remote
pool.
SELECT pool_cust_id
FROM ULCustomerIDPool
WHERE pool_cust_id = ?

108
Chapter 5 Synchronization Techniques

Handling conflicts
Conflicts arise during the upload of rows to the consolidated database. If two
users modify the same row, a conflict is detected when the second of the
rows arrives at the MobiLink synchronization server. When conflicts can
occur, you should define a process to compute the correct values, or at least
to log the conflict.
No conflicts arise in the remote database as a result of synchronization. If a
downloaded row contains a new primary key, the values are inserted into a
new row. If the primary key matches that of a pre-existing row, the other
values in the row are updated.
Conflicts are not the same as errors. Conflict handling can be an integral part
of a well-designed application, allowing concurrency, even in the absence of
locking.

How conflicts are detected


When the client updates any row of a table, it automatically retains a copy of
the values the row contained at the time of last synchronization. When you
next synchronize, your remote database contains not only the present data,
but also a record of the values that were present the last time you
synchronized.
When the client sends an updated row to the MobiLink synchronization
server, it includes not only the new values, but also a copy of the original
values. The MobiLink synchronization server processes each uploaded
update using the following procedure.
1 The MobiLink synchronization server compares the old uploaded values
to the current values of the row with the same primary-key values.
2 If the old uploaded values match the current contents in the consolidated
database, the MobiLink synchronization server detects no conflict.
♦ The MobiLink synchronization server updates the consolidated row
using the new uploaded values. You define the cursor that the
MobiLink synchronization server uses for this operation using the
upload_cursor table script. The old uploaded values are discarded.
3 If any of the old uploaded values do not match the current consolidated
values, the MobiLink synchronization server detects a conflict.
♦ The MobiLink synchronization server inserts the old values row
using the cursor defined by the old_row_cursor script.

109
Handling conflicts

♦ The MobiLink synchronization server inserts the new values row


using the cursor defined by the new_row_cursor script.
♦ The MobiLink synchronization server executes the resolve_conflict
script. In this script you can either call a stored procedure, or define
a sequence of steps to resolve the conflict as appropriate.

uploaded new
choose one
and old row
uploaded
values from one
row
remote table

Was this row


inserted or updated in
the remote
database?

update another row


insert
compare
old values
with matching conflict
consolidated
row
insert old values using
old_row_cursor script
values match

insert new values using


insert new row update row new_row_cursor script
using using
upload_rows upload_rows
script script execute
resolve_conflict
script

any more
uploaded rows?

no more rows

finished
inserts and updates
from this table

You can resolve conflicts as they occur using the resolve_conflict script, or
you can resolve all conflicts at once using the table’s end_upload script.

110
Chapter 5 Synchronization Techniques

Conflicts are detected only during updates of a row. If a row is deleted at one
remote database, and updated at another, the delete takes precedence, no
matter what order the actions are applied in.
$ You can gain finer control the conflict detection and resolution process.
For details, see "Programmatic conflict resolution" on page 111.

Programmatic conflict resolution


When no upload_cursor script is defined for a remote table, the MobiLink
synchronization server attempts to insert all uploaded rows from that table
using the cursors defined by the old_row_cursor and new_row_cursor
scripts. In essence, all uploaded rows are then treated as conflicts. You can
write stored procedures or scripts to process the uploaded values in any way
you want.
Without the upload_cursor script, the normal conflict-resolution procedure,
described above, is bypassed. This technique has two principal uses.
1 Manual conflict resolution The automatic mechanism only detects
errors when updating a row, and only then when the old values do not
match the present values in the consolidated database. Other, less
common, types of conflicts are possible.
♦ When processing an update, the MobiLink synchronization server
may find that the corresponding consolidated row is missing.
♦ When processing an insert, the MobiLink synchronization server
may find that the consolidated row already exits.
♦ When processing a delete, the MobiLink synchronization server
may find that the row has already been deleted.
You can capture the raw uploaded data using the old_row_cursor and
new_row_cursor scripts, then analyze it as you see fit.
2 Performance When the upload_cursor is not defined, the MobiLink
synchronization server is relieved of its normal conflict-detection tasks,
which involve querying the consolidated database one row at a time.
Instead, it needs only to insert the raw uploaded information using the
cursors defined by the old_row_cursor and new_row_cursor scripts.
Since only inserts are involved, the MobiLink synchronization server
performs these inserts using bulk operations that are more efficient.

111
Handling conflicts

Storing the user name


When you write old_row_cursor or new_row_cursor scripts, you can
include an extra column in your select statement. If you do so, the MobiLink
synchronization server automatically inserts the user name into the first
column, then uses the rest of the columns as usual. This mechanism is
available because some database-management systems provide no
convenient mechanism to store the identity of the current user.
You can use this feature to conveniently identify which user inserted each
row. This information allows you to include user-specific logic in the
resolve_conflict script.
For example, an ordinary old_row_cursor script is of the following form.
The items in the select list correspond to the columns of the remote table.
SELECT c1, c2, . . . , cN FROM table
However, the following syntax is also permitted.
SELECT user_name, c1, c2, . . . , cN FROM table
Normally, the selected columns must match the columns of the remote table
in both number and type. This case is an exception. The single extra column
in the select list must be of a type suitable to hold the user name; for
example, VARCHAR(128). The subsequent columns in the list must match
the columns of the remote table in order and type, as usual. If you include
more than one extra column, an error results.

112
Chapter 5 Synchronization Techniques

Miscellaneous techniques
The following techniques are also common.
♦ Data Entry In some databases, there will be tables that are only used
for data entry. During each synchronization, all rows inserted since the
last synchronization are uploaded. When the download stream is built,
all of these newly inserted rows will be removed from the Remote
database and the table will be empty again. This can be done by
uploading rows into a temporary table and inserting them into a base
table using an end_upload table script. The temporary table can be used
in the download_delete_cursor to remove rows from the Remote
database following a successful synchronization. Alternatively, you can
allow the client application to the delete the rows, using the
STOP SYNCHRONIZATION DELETE statement to stop the deletes
being uploaded during the next synchronization.
♦ Handling deletes When rows are deleted from the consolidated
database, there needs to be a record of the row so it can be removed
from any Remote databases that have the row.
One technique is to not delete the row. Data that is no longer required
can be marked as inactive by changing a status column in the row. The
download_cursor and download_delete_cursor can refer to the status
of the row in the WHERE clause. The CustDB sample application uses
this technique for the ULOrder table using the status column.
A second technique is to have a shadow table that stores the primary-key
values of deleted rows. When a row is deleted, a trigger can populate the
shadow table. The download_delete_cursor can use the shadow table to
remove rows from Remote databases. The shadow table only needs to
have the primary-key columns from the real table.
This technique is used in the ULEmpCust table in the sample
application, in which the action column holds a D for Delete. The scripts
use this value to delete the record from the Remote database, and delete
the record from the consolidated database at the end of the
synchronization.
♦ Handling failed downloads Bookkeeping information about what is
downloaded must be maintained in the download transaction. This
information is updated atomically with the download being applied to
the Remote database.

113
Miscellaneous techniques

If a failure occurs before the entire download stream is applied to the


Remote database, the MobiLink synchronization server does not get
confirmation for the download and rolls back the download transaction.
Since the bookkeeping information is part of the download transaction,
it is also rolled back. Next time the download stream is built, it will use
the original bookkeeping information.
When testing your synchronization scripts, you should add logic to your
end_download script that causes occasional failures. This will ensure
that your scripts can handle a failed download.

114
Chapter 5 Synchronization Techniques

Schema changes in remote databases


When the schema of a remote database changes, you need to re-generate the
UltraLite database and build a new application. The application needs to be
re-deployed and the new database populated by synchronizing with the
MobiLink synchronization server. It is usually impractical to have all users
upgrade to the new version of the application at the same time.
You need to be able to have both versions co-existing in the field and
synchronizing with a single consolidated database. You can create two or
more versions of the synchronization scripts that are stored in the
consolidated database and control the actions of the MobiLink
synchronization server. Each version of your application can then select the
appropriate set of synchronization scripts by specifying the correct version
name when it initiates synchronization.
The most common schema changes are to add a new column to an existing
table or to add a new table to the database.

Adding tables to remote databases


Adding a new table does not create any problem at all. You will have a new
row in ml_table and a new set of scripts that correspond to the new table.
When a user synchronizes, the upload stream contains a list of the tables in
the Remote database. The MobiLink synchronization server only expects
data for tables in this list. Only tables listed in the upload stream are
synchronized.

Changing table definitions in remote databases


Changing the number or type of columns in an existing table must be done
carefully. When a newer MobiLink client synchronizes, it expects cursor
scripts, such as upload_cursor, download_cursor, that have select lists for
all columns in the UltraLite table. An older UltraLite database expects cursor
scripts that have only the original columns.
To accommodate the various versions of your application, you can create
different versions of the synchronization scripts. Each time a client
synchronizes, it specifies the correct script version name. Using this
technique, an arbitrary number of versions of your application can co-exist
while synchronizing with a single consolidated database.

115
Schema changes in remote databases

116
C H A P T E R 6

Adaptive Server Anywhere Synchronization


using MobiLink – A Tutorial

About this chapter This chapter provides a tutorial that guides you through the process of
synchronizing two Adaptive Server Anywhere databases via MobiLink.
One of these databases is the consolidated database, the other is a remote
database. You create these databases and then synchronize the two.
Contents
Topic Page
Introduction 118
Creating a SQL file for the consolidated database 119
Running the synchronization tutorial 122
Summary 130

117
Introduction

Introduction
In this tutorial, you create a consolidated database and extract a remote
database. The tutorial then guides you to synchronize the two databases via
MobiLink.
In order to run the tutorial, you must first create a .sql file for the database.
Use the sample code in the section "Creating a SQL file for the consolidated
database" on page 119 to create a server.sql file. This file creates and
populates the tables in the consolidated database. In addition, this file also
includes scripts that specify the contents to be uploaded to the consolidated
database and downloaded to the remote database.

Reference versus consolidated databases


Do not confuse the reference and the consolidated database. Each has a
different role. The reference database is an Adaptive Server Anywhere
database that serves as a template for remote Adaptive Server Anywhere
databases. The consolidated database is a central store of data, connected
to the MobiLink synchronization server. The consolidated database can
have a different schema, or even be made using a different database-
management system. During this tutorial, you use the same database for
both purposes. You can do so only when the consolidated database is an
Adaptive Server Anywhere database and when the schema of the
consolidated database contains the union of the schemas of the remote
Adaptive Server Anywhere databases.

This tutorial assumes that you have installed Adaptive Server Anywhere on
Windows 95/98/NT.

v To prepare for the tutorial


♦ Create a directory to hold the files you will create: c:\synchtutorial.

118
Chapter 6 Adaptive Server Anywhere Synchronization using MobiLink – A Tutorial

Creating a SQL file for the consolidated


database
The following SQL commands create and insert data into the tables People
and Pets in the consolidated database. In addition, synchronization scripts
are inserted to produce the desired actions during MobiLink synchronization.
Because this database is an Adaptive Server Anywhere database, it can also
be used as a reference database. A reference database that serves as a
template for the remote database and the tables and columns of the remote
database will be a subset of those found in the reference database.
Copy the following code into a new file and save it as server.sql in your
c:\synchtutorial directory.
create table People (
person_id integer primary key,
fname varchar(30),
lname varchar(40),
notes varchar(500)
);
create table Pets (
pet_id integer primary key,
person_id integer,
name varchar( 30 ),
species varchar( 30 ),
foreign key person_id references People
);
insert
into People
values( 0, ’Alan’, ’Able’, ’good guy’ );
insert
into People
values( 1, ’Betty’, ’Best’, NULL );
insert
into Pets
values( 0, 0, ’Judy’, ’rat’ );
insert
into Pets
values( 1, 0, ’Carmel’, ’guinea pig’ );
insert
into Pets
values( 3, 1, ’Marshall’, ’cat’ );
commit;

119
Creating a SQL file for the consolidated database

call ml_add_table_script(
’version1’,
’People’,
’upload_cursor’,
’select person_id, fname, lname from People where
person_id=?’
);
call ml_add_table_script(
’version1’,
’People’,
’download_cursor’,
’select person_id, fname, lname from People’
);
call ml_add_table_script(
’version1’,
’Pets’,
’upload_cursor’,
’select pet_id, person_id, name, species from Pets
where pet_id=?’
);
call ml_add_table_script(
’version1’,
’Pets’,
’download_cursor’,
’select pet_id, person_id, name, species from Pets’
);
commit;

Explanation of the sample code


The server.sql sample code creates tables in the consolidated database,
inserts data into the tables, and stores synchronization scripts that specify
which data is to be uploaded to the consolidated database and downloaded to
the remote database.
Create tables The sample code creates two tables: People and Pets. The People table has
three columns: person_id, fname, lname, and notes. The Pets table also has
four columns: pet_id, person_id, name and species.
Insert data The following is the People table in the consolidated database after data has
been inserted:

person_id fname lname notes


0 Alan Able good guy
1 Betty Best (NULL)

120
Chapter 6 Adaptive Server Anywhere Synchronization using MobiLink – A Tutorial

The following is the Pets table in the consolidated database after data has
been inserted:

pet_id person_id name species


0 0 Judy rat
1 0 Carmel guinea pig
3 1 Marshall cat

Synchronization The synchronization scripts indicate that the first three columns in the People
scripts table should be uploaded to the consolidated database and downloaded to the
remote database, and all four columns in the Pets table are uploaded to the
consolidated database and downloaded to the remote database.

121
Running the synchronization tutorial

Running the synchronization tutorial


After you have created the server.sql file using the sample code in the
previous sections, you are ready to begin the tutorial.
In this tutorial, you build a consolidated database, a remote database, and
perform synchronization between the two.

Building the consolidated database


Follow these steps to build a consolidated database:
1 Create a new consolidated database.
In your c:\synchtutorial directory, use the following command to create a
consolidated database, master.db:
dbinit master.db
2 Start the consolidated database server.
Use the dbeng7 command as follows:
dbeng7 master.db
The database engine starts. The window minimizes automatically once
the engine has started successfully.
3 Start Interactive SQL and connect to the consolidated database.
♦ In your c:\synchtutorial directory, enter the following command:
start dbisql
♦ When the connection dialogue appears, enter master for the name
of the database server. Supply the user name DBA and the password
SQL. Click OK.
4 Add the database tables and synchronization scripts. To perform this
task, use the file server.sql, as described in "Creating a SQL file for the
consolidated database" on page 119.
To apply the statements to the master.db database, enter the following
command line in Interactive SQL:
♦ Choose Run Script from the File menu.
♦ Locate the file server.sql, then click Open.

122
Chapter 6 Adaptive Server Anywhere Synchronization using MobiLink – A Tutorial

The statements in the file are executed. Your consolidated database now
contains two tables with data: People and Pets. In addition,
synchronization scripts are stored in the consolidated database. These
scripts determine how the data in the upload stream is integrated into the
consolidated database and control the preparation of the download
stream.
5 Verify that tables have been created and data has been inserted
successfully.
♦ To display the contents of the People table, enter the following
command in the SQL Statements window. Choose Execute from the
SQL menu.
select * from People
♦ Use the following statement to display the contents of the Pets
table.
select * from Pets
6 Create a synchronization template. A synchronization template
identifies which tables and columns are to be replicated to a particular
server. Use the following statement to create this template.
CREATE SYNCHRONIZATION TEMPLATE testpub
TYPE ’tcpip’
ADDRESS ’host=localhost;port=2439;’
OPTION sv=’version1’
( TABLE People ( person_id, fname, lname ),
TABLE Pets
);
7 Create a synchronization site. A synchronization site identifies a
particular remote database. The description of this site is based on the
information in a particular synchronization template. Use the following
statement to create a site called demo_sync_site.
CREATE SYNCHRONIZATION SITE ’demo_sync_site’
USING testpub;
In the next section of this tutorial, you will create the appropriate
database for this site.
8 Disconnect from the reference database by executing the following SQL
statement.
disconnect

123
Running the synchronization tutorial

Extracting the remote database


1 Ensure that the consolidated database is still running. If it is not, restart
the server by entering the following command in your c:\synchtutorial
directory.
dbeng7 master.db
2 Extract the remote database.
♦ Enter the following command in your c:\synchtutorial directory.
Type the entire statement on one line.
mlxtract -c "dbn=master;uid=dba;pwd=sql"
-an remote.db
c:\synchtutorial demo_sync_site
This command causes the Sybase database extraction utility to connect
to your master database as user dba and create the database for site
demo_sync_site. The new database is called remote.db and is placed in
your c:\synchtutorial directory.
3 Shut down the database server.
♦ Right-click on the database server icon in the system tray. Select
Exit.
4 Start another engine for both the master and remote databases by issuing
the following command in your c:\synchtutorial directory.
dbeng7 master.db remote.db
5 Open a new window in Interactive SQL and connect to the remote
database.
♦ From Interactive SQL, select File➤New Window.
♦ On the Identification tab, supply the user name DBA and the
password SQL. On the Database tab, enter the database name
remote. Click OK.
When you have successfully connected, the new Interactive SQL
window displays.
6 Verify that tables have been created successfully. Note that the tables do
not yet contain any data.
♦ Enter the following command in Interactive SQL to display the
contents of the People table
select * from People
♦ Enter the following command in Interactive SQL to display the
contents of the Pets table

124
Chapter 6 Adaptive Server Anywhere Synchronization using MobiLink – A Tutorial

select * from Pets


7 Disconnect from the remote database by executing the following SQL
statement.
disconnect

Synchronizing the consolidated and remote databases


1 If the engine is not still running, start both the master and remote
databases by issuing the following command in your c:\synchtutorial
directory.
dbeng7 master.db remote.db
2 Create an ODBC data source for the master database. You create this
source because the MobiLink synchronization server can connect to the
database engine only through ODBC.
♦ Open the ODBC Data Source Administrator. From the Windows
Start menu, select Programs➤Sybase➤SQL Anywhere 7➤ODBC
Administrator.
♦ Add a data source for the master database. Click Add. In the Create
New Data Source dialogue, select Adaptive Server Anywhere 7.0,
then click Finish.
♦ Configure the new data source. Select the ODBC tab and supply the
Data source name MobiLink/ASA tutorial. Select the Login tab,
then supply the User ID dba and the password sql. Select the
Database tab and supply the Database file
c:\synchtutorial\master.db. Click OK.
♦ Click OK again to close the ODBC Data Source Administrator.
3 Start the MobiLink synchronization server.
The following command starts the MobiLink synchronization server and
identifies the ODBC data source MobiLink/ASA tutorial as the
consolidated database:
start dbmlsrv7 –c "dsn=MobiLink/ASA tutorial"
4 Synchronize the two databases.
Run the command dbmlsync as follows:
dbmlsync –c "dbn=remote;uid=dba;pwd=sql"
5 Verify that the data has transferred successfully.
♦ Reconnect to the remote database in Interactive SQL.

125
Running the synchronization tutorial

♦ Enter the following command in Interactive SQL to display the


contents of the People table
select * from People
♦ Enter the following command in Interactive SQL to display the
contents of the Pets table
select * from Pets
The People table in the remote database should appear as follows. Note
that the remote database lacks the notes column because that column
was not mentioned in the synchronization template.

person_id fname lname


0 Alan Able
1 Betty Best

The Pets table in the remote database should appear as follows.

pet_id person_id name species


0 0 Judy rat
1 0 Carmel guinea pig
3 1 Marshall cat

Modify the remote database


In this section, you make some changes to the remote database. Adaptive
Server Anywhere uses the synchronization definition to recognize which data
must be sent to the consolidated database when you next synchronize.
1 Add a new person to the remote database: In your Interactive SQL
window for the remote database, enter the following statement
insert into People values( 2, ’Charles’, ’Cutty’)
2 Add Charles’s pet guinea pig using the following statement.
insert into Pets
values( 4, 2, ’Hershey’, ’guinea pig’ )
3 Alan gives Carmel the guinea pig to Charles. Execute the following
statement to record the transfer.
update Pets
set person_id = 2
where name = ‘Carmel’

126
Chapter 6 Adaptive Server Anywhere Synchronization using MobiLink – A Tutorial

4 Add a new person.


insert into People values ( 3, ’Jerry’, ’Small’ );
5 Commit these changes.
commit
6 Verify your changes.
♦ Enter the following command in Interactive SQL to display the
contents of the People table
select * from People
♦ Enter the following command in Interactive SQL to display the
contents of the Pets table
select * from Pets
The People table in the remote database should appear as follows.

person_id fname lname


0 Alan Able
1 Betty Best
2 Charles Cutty
3 Jerry Small

The Pets table for both databases should appear as follows.

pet_id person_id name species


0 0 Judy guinea pig
1 2 Carmel guinea pig
3 1 Marshall cat
4 2 Hershey guinea pig

7 Disconnect from the remote database by executing the following SQL


statement.
disconnect

Upload changes made to the remote database


1 Ensure that the MobiLink synchronization server is still running. If it is
not, restart it as described previously in section "Synchronizing the
consolidated and remote databases" on page 125.

127
Running the synchronization tutorial

2 Synchronize the two databases.


Run the command dbmlsync as before:
dbmlsync –c "dbn=remote;uid=dba;pwd=sql"
3 Open a new window in Interactive SQL and connect to the master
database.
♦ From Interactive SQL, select File➤New Window.
♦ On the Identification tab, supply the user name DBA and the
password SQL. On the Database tab, enter the database name
master. Click OK.
When you have successfully connected, the new Interactive SQL
window displays.
4 Verify that the databases have been synchronized.
♦ Enter the following command in Interactive SQL to display the
contents of the People table
select * from People
♦ Enter the following command in Interactive SQL to display the
contents of the Pets table
select * from Pets
The People table in the master database should appear as follows.

person_id fname lname notes


0 Alan Able good guy
1 Betty Best (NULL)
2 Charles Cutty (NULL)
3 Jerry Small (NULL)

Notice that a new row for Charles Cutty is present. A new row for Jerry
Small is also present.
The Pets table for both databases should appear as follows.

pet_id person_id name species


0 0 Judy guinea pig
1 2 Carmel guinea pig
3 1 Marshall cat
4 2 Hershey guinea pig

128
Chapter 6 Adaptive Server Anywhere Synchronization using MobiLink – A Tutorial

The entry with a person_id of 3, which prior to synchronization only


existed in the consolidated database, now appears in both databases after
synchronization.
In addition, the inserts and updates made only to the remote database
prior to synchronization now apply to both databases after
synchronization. The consolidated database now also has the entries
with pet_id 4 and indicates that Charles Cutty now owns Carmel the
guinea pig.
5 Close your connections and exit Interactive SQL.
♦ Disconnect from the master database and from the remote database
by executing the following SQL statement in each Interactive SQL
window.
disconnect
♦ Exit Interactive SQL.
6 Shutdown the MobiLink synchronization server by issuing the following
command.
dbmlstop
7 Shutdown the database server.
♦ Right-click on the database server icon in the system tray. Select
Exit.

129
Summary

Summary
During this tutorial, you accomplished the following tasks.
♦ Created a new Adaptive Server database that served as both the
consolidated database and the reference database.
♦ Created a synchronization template and synchronization site that defined
which tables and columns were to be extracted for the remote database.
♦ Extracted a remote database, using the original database as the reference
database.
♦ Started a MobiLink synchronization server, using the original database
as the consolidated database, and synchronized the remote database in
order to download an initial set of data.
♦ Synchronized the remote database again, uploading your changes to the
consolidated database.

130
C H A P T E R 7

Adaptive Server Anywhere Clients

About this chapter This chapter describes how to use Adaptive Server Anywhere as a MobiLink
client.
Contents
Topic Page
Introduction 132
Synchronization definitions 134
Writing synchronization definitions 136
Initiating synchronization 138
Deployment management 141
The reference database 142
Extracting the remote databases 144
Partitioning data between remote sites 146
Temporarily stopping synchronization of deletes 147

131
Introduction

Introduction
Adaptive Server Anywhere databases can serve as remote databases in a
MobiLink setup, synchronizing with MobiLink synchronization servers
using functionality supplied with the database engine.

Adaptive Server
Anywhere

MobiLink
server

client
application

consolidated remote
database database

Two-way Data can be replicated in both directions. Definition statements, stored within
replication each Adaptive Server Anywhere remote database, specify which data in the
client database is to be synchronized with a particular synchronization server.
Synchronization scripts, stored in the consolidated database, guide the
MobiLink synchronization server in processing uploaded data and selecting
data for download to the client.

Processing and
downloaded rows

synchronization scripts

Synchronized columns
and uploaded rows
Consolidated synchronization Remote
database database
definitions

MobiLink clients initiate synchronization. To synchronize an Adaptive


Server Anywhere remote database, use the dbmlsync command-line utility.

132
Chapter 7 Adaptive Server Anywhere Clients

During the synchronization process, all synchronized data in the remote


database that has changed since the previous synchronization is uploaded to
the MobiLink synchronization server. The MobiLink synchronization server
incorporates these changes into the consolidated database, then selects
consolidated data that is to be sent to the client. When the client has
incorporated the downloaded data, it sends a confirmation message to the
server, completing the synchronization process.

133
Synchronization definitions

Synchronization definitions

To convert an Adaptive Server Anywhere database for use as a MobiLink


client, you create a synchronization definition in the remote database.
A synchronization definition is a database object describing the data in a
remote Adaptive Server Anywhere database that is to be synchronized and
the location of a particular MobiLink synchronization server with which to
synchronize it. Synchronization definitions are required only in Adaptive
Server Anywhere remote databases.
A single Adaptive Server Anywhere database can synchronize with more
than one MobiLink synchronization server. To allow synchronization with
multiple servers, create one synchronization definition for each server.
Example To synchronize the Customer and Sales_Order tables in a remote Adaptive
Server Anywhere database, you could create the following synchronization
definition in the remote database.
CREATE SYNCHRONIZATION DEFINITION testpub
SITE ’demo_sync_site’
TYPE ’tcpip’
ADDRESS ’host=localhost;port=2439;’
OPTION sv=’version1’
(table Customer,table Sales_Order);
The SITE clause specifies that this particular MobiLink client is to be known
to the MobiLink synchronization server by the unique name demo_sync_site.
Synchronization is to occur over a TCP/IP connection. The synchronization
server is to use the version1 version of the synchronization scripts when
interacting with this client.

Comparison to SQL Remote


Should you already be familiar with Sybase SQL Remote, you will
recognize that synchronization definitions are very similar to the
SQL Remote concept of publications. The data replicated by SQL Remote
is arranged in publications. Each database that shares information in a
publication must have a subscription to the publication. Unlike
publications, synchronization definitions are required only in the remote
database. In addition, unlike publications, synchronization definitions
include the connection parameters for one particular MobiLink
synchronization server.

Synchronization You can choose to synchronize all or any portion of the data in a remote
definitions define Adaptive Server Anywhere database. You can choose to synchronize entire
which remote data tables, or you can choose to synchronize only particular columns and rows.
is synchronized

134
Chapter 7 Adaptive Server Anywhere Clients

The synchronization definition, located in the remote Adaptive Server


Anywhere database, describes the data that is to be replicated and the
location of the appropriate MobiLink synchronization server.
Synchronization scripts, stored in the consolidated database, control how the
uploaded rows are processed and which rows are downloaded to the remote
site. These scripts do not depend on the type of remote database.
A synchronization definition may include data from several database tables.
Each table’s contribution to a synchronization definition is called an article.
Each article may consist of a whole table, or a subset of the rows and
columns in a table.

A two-table synchronization definition

á á á á á
á á á á á
á á á á á + á á
á á á á á á á
á á á á á á á
Article 1: all of Article 2: some rows and
table A columns from table B

Synchronizing a Once a remote database has been set up, the two databases must be
remote database periodically brought to a state where they both have the same set of
information. This process of updating the consolidated and remote databases
to be consistent is called synchronization. Synchronization is carried out
using the dbmlsync command-line utility.
Altering a A table, once added to a synchronization definition, should not be altered.
synchronized table Altering the table interferes with the synchronization process. Should it be
necessary to make such an alteration, this step should be performed
immediately following synchronization.
The only way to ensure that the ALTER STATEMENT is executed
immediately following synchronization is to place this statement in a script,
then execute that script using the -i switch of the dbmlsync command-line
utility.

135
Writing synchronization definitions

Writing synchronization definitions


The synchronization definition is a database object describing data in a
remote Adaptive Server Anywhere database that is to be replicated and the
location of a particular MobiLink synchronization server. A synchronization
definition is defined only in a remote database. MobiLink consolidated
servers are configured using scripts.
A synchronization definition specifies the following pieces of information
♦ name The name of the synchronization definition, known only within
the remote database.
♦ site A name that uniquely identifies this particular MobiLink client.
♦ type The type of stream to be used to communicate with the MobiLink
synchronization server.
♦ address The parameters necessary to connect to the MobiLink
synchronization server.
♦ script version The version of the synchronization scripts the
MobiLink synchronization server is to use when synchronizing this
client.
♦ articles A description of the data to be synchronized. You can
synchronize entire tables, or only particular rows and columns.

The following statement creates a synchronization definition named testpub


that defines what data is to be synchronized with site demo_sync_site.
CREATE SYNCHRONIZATION DEFINITION testpub
SITE ’demo_sync_site’
TYPE ’tcpip’
ADDRESS ’host=localhost;port=2439;’
OPTION sv=’version1’
(table People( person_id, fname, lname ),table Pets);
Note the following specific components of this statement.
♦ The name of this synchronization definition is testpub. This name is only
known within the remote database.
♦ The name demo_sync_site uniquely identifies this client to the
MobiLink synchronization server. This name should appear in the
ml_user MobiLink system table, located in the consolidated database.
♦ The synchronization is to occur over a TCP/IP connection. The
connection parameters appear in a string in the ADDRESS clause.

136
Chapter 7 Adaptive Server Anywhere Clients

♦ The MobiLink synchronization server is to use the set of


synchronization scripts identified by the name version1 when
synchronizing this client. This script version name should appear in the
ml_script_version MobiLink system table, located in the consolidated
database.
♦ All columns and rows of the Pets table and the listed columns of the
People table are to be synchronized.
The TCP/IP connection parameters, appearing as a string in the address
clause, show that the MobiLink synchronization server is listening on port
2439 of the current machine. Only the listed columns of the People table are
synchronized. The option clause is included to indicate that the MobiLink
synchronization server should use version1 of the synchronization scripts
when processing data from this client. The default value of this parameter is
default. Notice that the list of columns is also enclosed in parentheses.
$ For a complete description of the syntax, see "CREATE
SYNCHRONIZATION DEFINITION statement" on page 197.
Comparison to If you have developed UltraLite applications for use as MobiLink clients, the
UltraLite clients following information may be helpful. Many of the elements of a
synchronization definition have an UltraLite counterpart.

Adaptive Server UltraLite client MobiLink


Anywhere client synchronization calls synchronization server
name data structure identifier none
site user name MobiLink user name
type stream connection type
address connection parameters location of server
script version (sv) version script version
articles none—all UltraLite tables none
are synchronized

Synchronizing with To synchronize a remote Adaptive Server Anywhere database with multiple
multiple servers MobiLink synchronization servers, create multiple synchronization
definitions within the remote database. Each synchronization definition must
have a unique site name because, from the point of view of the MobiLink
synchronization server, each is a separate logical client.
Synchronizing the same data in one remote database with multiple MobiLink
synchronization servers is not presently supported.

137
Initiating synchronization

Initiating synchronization
MobiLink synchronization is always initiated by the client. In the case of an
Adaptive Server Anywhere client, synchronization is initiated by running the
dbmlsync utility on the client. This utility connects to a remote Adaptive
Server Anywhere database.
Connection parameters for the remote Adaptive Server Anywhere database
must be specified on the dbmlsync command line using the -c switch.
Do not specify the connection parameters for the MobiLink synchronization
server. Information in the synchronization definition within the remote
database is used to connect to the appropriate MobiLink synchronization
server.
Permissions for When dbmlsync connects to a database, it must have permissions to apply all
dbmlsync the changes being made. The dbmlsync command line contains the password
for this connection. This could present a security issue.
To avoid security problems, you can grant a user REMOTE DBA authority,
and use this user ID in the dblmsync connection string. A user ID with
REMOTE DBA authority has DBA authority when the connection is made
from the dbmlsync utility, but no special authority from any other
application.
$ This REMOTE DBA authority method is also used by the SQL Remote
Message Agent. For more information, see "The Message Agent and
replication security" on page 457.
Transaction log To prepare the upload stream, the dbmlsync utility requires access to all
files transaction logs written since the previous synchronization. The transaction-
logs directory is the directory that contains previous transaction log files for
the remote Adaptive Server Anywhere client database. If the transaction log
has been truncated and renamed since the previous synchronization, specify
the directory that contains the renamed log files on the command line.
You may omit this parameter only if the working log file has not been
truncated and renamed since you last synchronized, or if the dbmlsync utility
is run from the directory that contains the renamed log files. Log files are
commonly renamed and truncated when backing up the database, so it may
be necessary to specify the transaction logs directory if you have backed up
the remote database since you last synchronized.
For the same reason, it is essential that old log files be saved until a more
recent synchronization has completed successfully.

138
Chapter 7 Adaptive Server Anywhere Clients

Example Suppose that you have remote database named remote. This database, which
is currently running on your local machine, contains the appropriate
synchronization definition to allow the correct information to be
synchronized with the intended MobiLink synchronization server. In
addition, assume that the MobiLink synchronization server has been started.
You could use the following command to synchronize as user DBA.
dbmlsync –c "dbn=remote;uid=dba;pwd=sql" c:\data
This command assumes that the log files for this database are located in the
directory c:\data.
If the remote database contains more than one synchronization definition,
you must specify a particular synchronization definition using the -n switch.
In particular, you must use this feature if the remote database contains
multiple MobiLink clients.
Scheduling Presently, no scheduling utility is provided to allow you to synchronize at
synchronization particular times or at particular time intervals. Instead, use the scheduling
tools available on your operating system to run the dbmlsync utility at the
required time intervals.
$ For a list of the available parameters, see "Adaptive Server Anywhere
client synchronization utility" on page 161.

Other concurrent connections


During synchronization, the dbmlsync utility requires exclusive write access
to all tables in the synchronization definition. No other application can
modify these tables at the same time. If synchronization is initiated when
there are other connections to the remote database, write locks held by these
connections can prevent synchronization from proceeding. In this case,
synchronization is delayed until the other connections release their locks.
Sometimes, as is often the case for embedded applications, it may be
possible to schedule synchronization only when no other operations are
occurring in the remote database. Even when the remote database is used by
a number of users or applications, it may be possible to find times of no
activity during which synchronization can safely occur.
Once synchronization commences, other users are denied write access to the
synchronized data. All process requiring write access to the synchronized
data must wait for the synchronization process to complete. The duration of
this delay depends upon the amount of data to be exchanged, the speed of the
connection to the MobiLink synchronization server, and the load on the
server itself.

139
Initiating synchronization

Forcing other In some applications, it is essential that synchronization proceed as planned.


connections to In such situations, you can use the -d switch to force the remote database to
close drop all other connections that are presently using resources required for
synchronization.
When you do so, synchronization will proceed almost immediately, but other
connected users or applications may be abruptly disconnected. Uncommitted
changes are rolled back, so these users or applications must reconnect later to
repeat any incomplete transactions.

140
Chapter 7 Adaptive Server Anywhere Clients

Deployment management
To deploy multiple Adaptive Server Anywhere clients, you must first create
the required remote databases and fill these databases with initial data.
In addition, you must create a synchronization definition in each remote
database. This database object specifies the synchronized data, the MobiLink
connection parameters, and the client’s unique name.
You can create each remote database individually using standard
administration tools such as Sybase Central, but Adaptive Server Anywhere
also includes specialized tools to facilitate this task.
When developing Adaptive Server Anywhere clients, you will be working
with the following tools.
♦ A reference database A reference database is an Adaptive Server
Anywhere database that serves as a template of the remote Adaptive
Server Anywhere databases.
♦ A database extraction utility An extraction utility called mlxtract
creates each remote database based on information in the reference
database.

Creating multiple remote databases


The following procedure allows you to efficiently create a multiple Adaptive
Server Anywhere remote databases.

v To create Adaptive Server Anywhere client databases


1 Create an Adaptive Server Anywhere reference database.
2 Create one or more synchronization templates in the reference database.
Each synchronization template serves as a model of the synchronization
definition to be created in one type of remote site.
3 Create one synchronization site for each remote database, giving each
site a unique name.
4 Using the mlxtract command-line utility, create each remote database in
turn.
$ For information about the reference database, see "The reference
database" on page 142.
$ For information about extracting the remote databases, see "Extracting
the remote databases" on page 144.

141
The reference database

The reference database


A reference database is an Adaptive Server Anywhere database that serves
as the template of the remote Adaptive Server Anywhere databases that you
plan to create.
The schema of the reference database must contain the union of the schemas
of the remote databases. In other words, each remote database must contain a
subset of the tables, columns, and indexes found in the reference database.
The schema of the reference database may, but need not, be similar to the
schema of the consolidated database.
In addition to the database schema, you must create two types of database
objects within the reference database.
♦ synchronization template A synchronization template is a template
of the synchronization definition statements that are to appear in the
remote databases. It typically contains all the information in the
synchronization definitions, except for the client name, which would
normally appear in the SITE clause.
♦ synchronization sites A synchronization site is an object that
specifies which synchronization template is to be used when creating a
specific client. You create one synchronization site object for each
Adaptive Server Anywhere remote database you plan to create.
A typical reference database contains one synchronization template and
multiple synchronization sites, one for each remote Adaptive Server
Anywhere database. Each synchronization site specifies the MobiLink client
name.
Creating templates A synchronization template is similar to a synchronization definition. Thus, a
and sites synchronization template is created in almost the same manner. The major
difference is that a template contains no SITE clause, since the client names
are specified separately.
CREATE SYNCHRONIZATION TEMPLATE ClientTypeOne
TYPE ’tcpip’
ADDRESS ’host=localhost;port=2439;’
OPTION sv=’version1’
(table People( person_id, fname, lname ),table Pets);
Once you have created a template, you can use it to create multiple
synchronization sites. For example, the following statement creates a client
named demo_sync_site.
CREATE SYNCHRONIZATION SITE demo_sync_site
USING ClientTypeOne
Create one site for each remote database.

142
Chapter 7 Adaptive Server Anywhere Clients

Creating different A synchronization site can also override information contained in the
types of sites synchronization template. This feature is useful when a few sites require
different settings.
When remote sites differ significantly, you can create a separate
synchronization site for each type of client and specify the appropriate
template when you create each synchronization site.

The reference versus the consolidated database


Do not confuse the reference database with the consolidated database. The
consolidated database serves as the master repository of data in your
replication system. The reference database is a template from which you can
extract remote databases.
The following characteristics differentiate the reference database from the
consolidated database.
♦ database product The reference database must be built with Adaptive
Server Anywhere. In contrast, MobiLink supports a number of database
products in the role of consolidated database, including Sybase Adaptive
Server Anywhere, Sybase Adaptive Server Enterprise, Oracle, and
IBM DB2.
♦ presence of data The consolidated database is the master repository
of information in the synchronization system. In contrast, the reference
database need not contain data. Optionally, you can populate the
reference database with data that you want the remote databases to
contain initially.
♦ schema The schema of the reference data is a template for the remote
databases. In contrast, MobiLink technology allows the consolidated
database to have a different structure. For example, the data stored in a
particular table and column at one client can be stored in a different
table and column at another client, and in yet another location at the
consolidated database.

Can a consolidated When the following conditions are satisfied, a consolidated database can
database function serve as a reference database. Using one database for both purposes is
as a reference convenient, as you need maintain only one database instead of two.
database?
♦ The consolidated database must be created with Adaptive Server
Anywhere.
♦ The schema of the consolidated database must be a superset of the union
of the schemas at the remote sites. In other words, the tables and
columns at each remote site must exist in the consolidated database.

143
Extracting the remote databases

Extracting the remote databases


The mlxtract command-line utility is used to create each remote database.
Each remote database is created using a unique synchronization site,
contained in the reference database.
Run the mlxtract command-line utility once for each remote database.
Specify a different synchronization site name is each time. This process is
called extracting the remote databases because the remote databases are
created from the reference database.
The mlxtract command-line utility unloads a database schema suitable for
building a remote Adaptive Server Anywhere database for a named site. It
writes an SQL-language command file with the default name reload.sql. This
file includes a fully qualified synchronization definition. By default, only the
schema and synchronization definition are extracted. Use the -id command-
line switch to also extract an initial set of data.
Preparing to You must complete the following tasks before extracting the remote
extract databases.
♦ Create a reference database.
♦ Define the tables and columns that are to appear in the remote databases.
♦ Create one more synchronization template using the CREATE
SYNCHRONIZATION TEMPLATE statement.
♦ Create one synchronization definition for each remote database using the
CREATE SYNCHRONIZATION SITE statement.

v To extract a remote database


1 Run the mlxtract command-line utility, specifying the name of the client.
The utility writes a reload.sql command file for the named client.
2 Create an Adaptive Server Anywhere database using Sybase Central or
the dbinit command-line utility.
3 Start the new database.
4 Connect to the new database from Interactive SQL:
5 Run the reload command file by entering the following statement in the
Interactive SQL window:
read path\reload.sql

Optionally, you can use the -an switch for mlxtract to combine these steps
into one operation.

144
Chapter 7 Adaptive Server Anywhere Clients

The format of Adaptive Server Anywhere database files is independent of


both operating system and file system. You can create the database under one
operating system, then copy the database and log file to another machine. For
example, you could create a database on a Windows machine, then copy it to
a UNIX machine and use it with an Adaptive Server Anywhere server
running there.

Tip
The database extraction utility is intended to assist in preparing remote
databases, but is not a black box solution in all circumstances. To provide
custom solutions, you can edit the reload.sql command file. In particular,
if you are extracting a very large number of clients, you may find it more
efficient to run the mlxtract utility only once, then customize the
reload.sql command file for each client.

$ For an example of how these commands are used to extract a remote


site, see "Adaptive Server Anywhere Synchronization using MobiLink – A
Tutorial" on page 117.

Before extracting a remote database


The extraction utility relies on a reference database. A reference database is
an Adaptive Server Anywhere database that contains a superset of the tables
and columns that will exist at the remote sites. The extraction utility uses the
reference database as a template when creating the reload scripts for the
remote databases.
In addition, you must define a synchronization template and a
synchronization site that describe the requirements of the remote databases.
A synchronization template is very similar to a synchronization definition,
but instead of defining a complete synchronization definition for the current
database, it acts as a template for the creation of remote sites.
You create particular instances of remote sites using the CREATE
SYNCHRONIZATION SITE statement. Each site relies on a particular
synchronization template. Your reference database can contain more than
one synchronization template and many synchronization sites can use the
same template. Each synchronization site, however, can use only one
template.

145
Partitioning data between remote sites

Partitioning data between remote sites


It is common for remote sites to fall into separate categories, each with their
own requirements. Consider a sales application. All the sales personnel in
one region may require access to a particular set of data, but not require
access to information about regions other than their own. Employees in other
departments may require data of an entirely different nature. Managers may
require data that should not be accessible to their subordinates.
Synchronization templates are typically used to specify fundamentally
different sets of data. For example, you can create one template for the sales
staff and another template for those employees who do technical support.
You can further fine-tune the data any given remote database will receive by
using a conditional clause within the synchronization definition. This feature
is useful when remote sites require similar types of information. For
example, it can be used to provide sales representatives with only the
information relevant to their region.
Example Assume that you have three different categories of personnel at your
company: manager, sales agent, and consultant. All employees in your
company that you wish to deploy fall within one of the above categories. The
personnel in each category require a different synchronization schema from
the personnel in other categories. For example, the managers require a
different set of tables from the sales agents and consultants. The sales agents
will require a different set of tables from the managers and consultants. The
consultants require a different set of tables from the other two groups.
Using templates, you can easily generate and re-generate databases for
deployment. If you decide to change the remote databases, for example add a
new table, you only need to modify the reference database, then re-extract
the remote sites.
Since each group requires a different schema, you should create three
different synchronization templates in the reference database, one template
for each group. Next, create a synchronization site in the reference database
for each remote database. When creating each site, use the template that best
suites the user’s requirements. Finally, create the remote databases using the
mlxtract command-line utility.
$ For information on mlxtract, see "Adaptive Server Anywhere client
database extraction utility" on page 157.

146
Chapter 7 Adaptive Server Anywhere Clients

Temporarily stopping synchronization of deletes


Ordinarily, Adaptive Server Anywhere automatically logs any changes to
tables or columns that are part of a synchronization definition. These changes
are uploaded to the consolidated database during the next synchronization.
There can be circumstances, however, when you wish to delete rows from
synchronized data and not have those changes uploaded. This feature can be
used to make unusual corrections, for example, but should be used with
caution as it effectively disables part of the automatic synchronization
functionality. This technique is a practical alternative to deleting the
necessary rows using a download_delete_cursor script
When a STOP SYNCHRONIZATION DELETE statement is executed, none
of the delete operations subsequently executed on that connection are
synchronized. The effect continues until a START SYNCHRONIZATION
DELETE statement is executed or until the transaction is terminated by a
COMMIT or ROLLBACK statement, whichever comes first. The effects do
not nest; that is, subsequent executions of stop synchronization delete after
the first will have no additional effect.

v To temporarily disable upload of deletes made through a connection


1 Issue the following statement to stop automatic logging of deletes.
STOP SYNCHRONIZATION DELETE
2 Delete rows from the synchronized data, as required, using the DELETE
statement. Commit these changes.
3 Restart logging of deletes using the following statement.
START SYNCHRONIZATION DELETE

The deleted rows will not be sent up to the MobiLink synchronization server
and hence will not be deleted from the consolidated database..

147
Temporarily stopping synchronization of deletes

148
C H A P T E R 8

Reference

About this chapter This chapter provides reference information about the MobiLink utility
programs, the MobiLink synchronization server synchronization scripts, and
the SQL statements used when working with Adaptive Server Anywhere
clients.
Contents
Topic Page
Utility programs 150
MobiLink system tables 167
Data-type conversions 168
Scripts 173
Stored procedures 190
SQL statements 192

149
Utility programs

Utility programs
The following utilities are required to build and synchronize UltraLite
applications.
$ For information about other Adaptive Server Anywhere utilities, see
"Database Administration Utilities" on page 71 of the book ASA Reference.

MobiLink synchronization server


The MobiLink synchronization server lets you synchronize your remote
databases with any ODBC-compliant consolidated database.
Syntax dbmlsrv7 [ switches ] –c "keyword=value; …"

Switch Description
–a Disable automatic reconnection upon
synchronization error.
–bc size Specify the amount of memory to reserve for
blob caching.
–bn size Specify the maximum number of bytes to
consider when comparing blobs.
–c "keyword=value; …" Supply ODBC database connection parameters
for your reference database
–cn connections Set maximum number of connections with the
consolidated database server.
–dl Display log messages on the console.
–o logfile Log messages to this file.
–os size Maximum size of output file.
–ot logfile Truncate file and log output messages to file.
–q Minimize the synchronization server window
–r retries Retry deadlocked uploads at most this many
times.
–rd delay Maximum delay, in seconds, before retrying a
deadlocked transaction.
–s count Specify the maximum number of rows to be
fetched at once.

150
Chapter 8 Reference

Switch Description
–u size Specify the amount of memory to reserve for
caching upload streams.
–ud On UNIX platforms, run as a daemon.
–vlevels Controls the type of messages written to the log
file.
–w count Set the number of worker threads.
–x protocol{keyword=value; …} Specify the communications protocol.

Description The MobiLink synchronization server opens connections, via ODBC, with
your consolidated database server. It then accepts connections from remote
applications and controls the synchronization process.
Because the MobiLink synchronization server is separate from the database
engine, and communicates through an ODBC connection, it is compatible
with a variety of database-management systems, including Adaptive Server
Anywhere, Adaptive Server Enterprise, Oracle, Microsoft SQL Server, and
IBM DB2.
You must supply the connection parameters for the consolidated database
using the –c option.
Switches –a When an error occurs during synchronization, the MobiLink
synchronization server automatically disconnects from the consolidated
database, then re-establishes the connection. Some database servers, such as
Adaptive Server Anywhere, maintain state information associated with each
connection. Reconnecting ensures the following synchronization starts from
a known state. When this behavior is not required, you can use this switch to
disable it.

–bc size The amount of memory to use for caching blobs. If more memory
is required, the MobiLink synchronization server uses disk space, instead.
For this reason, too small a value can degrade performance. To calculate the
minimum recommended size, multiply the maximum size of all blob data in
any one row by the number of worker threads, then multiply the result by 4.
The size is the amount of memory to reserve in bytes. Use the suffix "k" or
"m" to specify units of kilobytes or megabytes, respectively.

–bn size When two large blobs contain similar or identical values, the
operation of comparing them can be expensive due to the amount of data
involved. This tells the MobiLink synchronization server to consider only the
first size bytes of two blobs when making the comparison. The default is to
consider the entire blobs, no matter how big they are.

151
Utility programs

Under some situations, limiting the maximum amount of data compared can
speed synchronization substantially; however, it can also cause errors. For
example, if two large blobs differ only in the last few bytes, the MobiLink
synchronization server may decide that they are identical when in fact they
are not. Choose the value for this option carefully.

–c The connection string must give the MobiLink synchronization server


permission to connect to the consolidated database using an ODBC data
source. This parameter is required.

–cn connections This option specifies the maximum number of


connections that the MobiLink synchronization server should make to the
consolidated database. The minimum and the default value is one greater
than the number of worker threads. A warning is issued if the supplied value
is too small. A value much larger than the number of worker threads may
speed performance, particularly if connecting to the consolidated database is
slow or if multiple script versions are in use.

–dl Display messages in the window or on the command line and also in
the log file, if specified.

–o logfile Write all log messages to the specified file.

–os size The size is the maximum file size for logging output messages,
specified in units of bytes. Use the suffix "k" or "m" to specify units of
kilobytes or megabytes, respectively. By default, there is no size limit. The
minimum size limit is 10 kb.
Before the MobiLink synchronization server logs output messages to a file, it
checks the current file size. If the log message will make the file size exceed
the specified size, the MobiLink synchronization server renames the output
file to yymmddnn.log, where nn is a two-digit integer between 00 and 99 and
yymmdd represents the final two digits of the current year, the month, and the
day of the month.
This option allows you to manually delete old log files and free up disk
space.

–ot logfile Truncate the log file and then append output messages to it.
The default is to send output to the screen.

–q Minimize the MobiLink synchronization server window.

–r retries By default, MobiLink synchronization server retries uploads that


are deadlocked for a maximum of 10 attempts. If the deadlock is not broken,
synchronization fails, since there is no guarantee that the deadlock can be
overcome. This option allows an arbitrary retry limit to be set. To stop the
server from retrying deadlocked transactions, specify –r 0.

152
Chapter 8 Reference

–rd delay When upload transactions are deadlocked, the MobiLink


synchronization server waits a random length of time before retrying each
transaction. The random nature of the delay greatly increases the likelihood
that future attempts will succeed. This switch allows you to specify the
maximum delay in units of seconds. The value 0 (zero) makes retries
instantaneous, but larger values are recommended because they yield more
successful retries. The default delay value is 30.

–s count Set the number of rows fetched at one time from the database
to count. Set this option to no less than the number of rows specified in the
ODBC pre-fetch option, if this option is set. The default value is 10.

–u size The amount of space, in units of bytes, to reserve for caching


upload streams that are being processed. Use the suffix "k" or "m" to specify
units of kilobytes or megabytes, respectively. You should consider enlarging
this value if your clients upload large streams, or many clients synchronize at
once, or both. The suggested size is the maximum expected size of the
upload stream multiplied by the number of worker threads. The default value
is 500 kb.

–ud On UNIX platforms, you can run the MobiLink synchronization


server as a daemon by supplying the -ud command-line switch.

–v level This option controls the type of messages written to the log file.

The allowed values of levels and their meanings are as follows. You can use
two or more of these options at once. If you specify –v alone, the MobiLink
synchronization server writes a minimal amount of information about each
synchronization.
♦ c Show the content of each synchronization script when it is invoked.
This level implies s.
♦ n Show row-count summaries.
♦ r Display the column values of each row uploaded or downloaded.
♦ s Show the name of each synchronization script as it is invoked.
♦ t Show the translated SQL that results from scripts that are written in
ODBC canonical format. This level implies c. The following example
shows the automatic translation of a statement for Adaptive Server
Anywhere.
I. 02/11 11:02:14. [102]: begin_upload synch2
{ call SynchLogLine( ?, ?, ’begin_upload’ ) }
I. 02/11 11:02:14. [102]: Translated SQL:
call SynchLogLine( ?, ?, ’begin_upload’ )

153
Utility programs

The following example shows the translation of the same statement for
Microsoft SQL Server.
I. 02/11 11:03:21. [102]: begin_upload synch2
{ call SynchLogLine( ?, ?, ’begin_upload’ ) }
I. 02/11 11:03:21. [102]: Translated SQL:
EXEC SynchLogLine ?, ?, ’begin_upload’

–w count Set the number of worker threads. Each worker thread accepts
synchronization requests one at a time. These threads are allocated as
follows.
♦ A single thread is dedicated to each serial stream.
♦ The remaining threads are available for TCP/IP connections.
Each worker thread opens one connection to the consolidated database. The
MobiLink synchronization server opens one additional connection for
administrative purposes. Hence, the minimum number of connections from
the MobiLink synchronization server to the consolidated database is
count + 1.

–x protocol Specify communications protocol through which to


communicate with remote applications.

The allowed values of protocol and their meanings are as follows:


♦ serial Accept serial connections from applications.
♦ tcpip Accept connections from applications via TCP/IP.
♦ http Accept connections via the standard web protocol.
Optionally, you can append a list of semi-colon separated parameters, of the
form keyword=value. To append parameters, enclose them in curly braces.
The permitted parameters are as follows:
♦ Serial port parameters These are chosen from the following list:
♦ baud=integer The BAUD rate at which information is to be
passed through the serial connection. The default is 19200 BAUD.
♦ port=integer The COM port to use for the serial connection.
Typically, the port number is 1, which represents COM1: on a
standard PC.

154
Chapter 8 Reference

♦ security=cipher{keyword=value;…} All communication through


this connection is to be encrypted using the cipher suite specified.
You can use only one cipher suite at a time. The only cipher suite
presently supported is certicom_tls, Certicom transmission-layer
security. The security keywords presently available are certificate,
the certificate that is to be used for server authentication, and
certificate_password.
A sample certificate named mobilink.crt is included with Adaptive
Server Anywhere. The password for this certificate is tJ1#m6+W.
This certificate is used by default. Thus, the default certificate name
is mobilink.crt and the default certificate password is tJ1#m6+W.
This sample certificate is to be used for testing and development
work only. The sample server authentication certificate provides no
security because the same certificate and password are distributed
to all Adaptive Server Anywhere customers. When deploying a
secure system, it is essential that you obtain and use your own
personal certificate and password. New certificates are available
from Certicom.
$ For a further explanation, see "Transport-layer security" on
page 51.
♦ timeout=t The length of time (in seconds) that the server waits for
a serial connection read request before abandoning the connection.
This parameter can be useful to ensure that connections are
abandoned after a certain amount of time has elapsed. However,
short timeout periods can cause the MobiLink synchronization
server to issue inappropriate error messages because devices with
relatively slow processors can take several minutes to process a
large download stream. The default value for the timeout parameter
is 300 seconds. The value 0 can be used to specify no timeout.
♦ TCP/IP parameters These are chosen from the following list:
♦ host=hostname The host name or IP number on which the
MobiLink synchronization server should listen. The default value is
localhost.
♦ port=portnumber The socket port number to on which the
MobiLink synchronization server should listen. The port number
must be a decimal number that matches the port the MobiLink
synchronization server is set up to monitor. The default value for
the port parameter is 2439, which is the IANA registered port
number for the MobiLink synchronization server.

155
Utility programs

♦ security=cipher{keyword=value;…} All communication through


this connection is to be encrypted using the cipher suite specified.
You can use only one cipher suite at a time. The only cipher suite
presently supported is certicom_tls, Certicom transmission-layer
security. The security keywords presently available are certificate,
the certificate that is to be used for server authentication, and
certificate_password.
A sample certificate named mobilink.crt is included with Adaptive
Server Anywhere. The password for this certificate is tJ1#m6+W.
Use of this sample certificate is for testing and development work
only. The sample server authentication certificate provides no
security because the same certificate and password are distributed
to all Adaptive Server Anywhere customers. When deploying a
secure system, it is essential that you obtain and use your own
personal certificate and password. New certificates are available
from Certicom.
$ For a further explanation, see "Transport-layer security" on
page 51.
♦ HTTP stream parameters These are chosen from the following list:
♦ host=hostname The host name or IP number on which the
MobiLink synchronization server should listen. The default value is
localhost.
♦ port=portnumber The socket port number on which the
MobiLink synchronization server should listen. The port number
must be a decimal number that matches the port the MobiLink
synchronization server is setup to monitor. The default value for the
port parameter is 80.
♦ security=cipher{keyword=value;…} All communication through
this connection is to be encrypted using the cipher suite specified.
You can use only one cipher suite at a time. The only cipher suite
presently supported is certicom_tls, Certicom transmission-layer
security. The security keywords presently available are certificate,
the certificate that is to be used for server authentication, and
certificate_password.

156
Chapter 8 Reference

A sample certificate named mobilink.crt is included with Adaptive


Server Anywhere. The password for this certificate is tJ1#m6+W.
Use of this sample certificate is for testing and development work
only. The sample server authentication certificate provides no
security because the same certificate and password are distributed
to all Adaptive Server Anywhere customers. When deploying a
secure system, it is essential that you obtain and use your own
personal certificate and password. New certificates are available
from Certicom.
$ For a further explanation, see "Transport-layer security" on
page 51.
♦ url_suffix=suffix The suffix to add to the URL on the first line of
each HTTP request. This parameter can be used to help ensure that
a particular client connects to the intended server.
♦ version=versionnumber A string specifying the version of HTTP
to use. You have a choice of 1.0 or 1.1. The default value is 1.1.

MobiLink synchronization server stop utility


This utility stops the MobiLink synchronization server if it is currently
running.
Syntax dbmlstop
Description Running this command stops the MobiLink synchronization server. If any
applications are currently synchronizing, these synchronizations are aborted.

Restriction
The MobiLink Synchronization server stop utility can only stop a
MobiLink synchronization server that is listening to a TCP/IP socket on
the current machine at the default port. In other words, the stop utility
only sends the stop message to port 2349 at the address localhost.

Adaptive Server Anywhere client database extraction utility


Purpose To extract a remote Adaptive Server Anywhere database from a reference
Adaptive Server Anywhere database.
Syntax mlxtract [ additional switches ] directory site-name

157
Utility programs

Switch Description
–ac "keyword=value; ..." Connect to the database specified in the connect string to do
the reload.
–an database Creates a database file with the same settings as the
database being unloaded and automatically reloads it.
–c "keyword=value; ..." Supply database connection parameters.
–id Extract schema definition and data.
–it Extract triggers.
–j count Iteration count for view-creation statements.
–l level Perform all extraction operations at specified isolation level.
–o file Output messages to file.
–p character Escape character.
–q Operate quietly: do not print messages or show windows.
–r file Specify name of generated reload Interactive SQL command
file (default "reload.sql").
–u Unordered data.
–v Verbose messages.
–x Use external table loads.
–xf Exclude foreign keys.
–xp Exclude stored procedures.
–xv Exclude views.
–y Overwrite command file without confirmation.
directory The directory to which the files are written. This switch is
not needed if you use -an or -ac.
site-name Specify which remote site to generate.

Description mlxtract is the MobiLink extraction utility for Adaptive Server Anywhere
client databases. It is run against an Adaptive Server Anywhere reference
database and creates a command file for a remote Adaptive Server Anywhere
database.
The command line extraction utility creates a command file and a set of
associated data files. The command file can be run against a newly initialized
Adaptive Server Anywhere database to create the database objects and load
the data for the remote database.
By default, the command file is named reload.sql.

158
Chapter 8 Reference

Switches Reload the data to an existing database (–ac) You can combine the
operation of unloading a database and reloading the results into an existing
database using this option.
For example, the following command (which should be entered all on one
line) loads a copy of the data for the field_user subscriber into an existing
database file named newdemo.db:
mlxtract -c "uid=dba;pwd=sql;dbf=asademo.db" -ac
"uid=dba;pwd=sql;dbf=newdemo.db" field_user
If you use this option, no copy of the data is created on disk, so you do not
specify an unload directory on the command line. This provides greater
security for your data, but at some cost for performance.

Reload the data to a new database (–an) You can combine the
operations of unloading a database, creating a new database, and loading the
data using this option.
For example, the following command (which should be entered all on one
line) creates a new database file named asacopy.db and copies the schema
and data for the field_user subscriber of asademo.db into it:
mlxtract -c "uid=dba;pwd=sql;dbf=asademo.db" -an
asacopy.db field_user
If you use this option, no copy of the data is created on disk, so you do not
specify an unload directory on the command line. This provides greater
security for your data, but at some cost for performance.

Connection parameters (–c) A set of connection parameters, in a string.


♦ mlxtract connection parameters The user ID should have DBA
authority to ensure that the user has permissions on all the tables in the
database.
For example, the following statement (which should be typed on one
line) extracts a database for remote user ID joe_remote from the
asademo database running on the sample_server server, connecting as
user ID DBA with password SQL. The data is unloaded into the
c:\unload directory.
mlxtract -c "eng=sample_server;dbn=sademo;
uid=dba;pwd=sql" c:\extract joe_remote

Extract both schema definition and data (–id) By default, only the
schema is extracted. Such a database can be initialized with data upon the
first connection to a MobiLink synchronization server. This switch provides
the alternative of loading the initial data into the reference database and
initializing the new database as part of the extraction procedure.

159
Utility programs

Extract both schema definition and data (–it) By default, only the
schema and synchronization definition are extracted. Triggers are not
extracted. This switch provides the option of extracting the triggers present
in the reference database.

Iteration count for views (–j) If there are nested views in the
consolidated database, this option specifies the maximum number of
iterations to use when extracting the views.

Perform extraction at a specified isolation level (–l) The default


setting is an isolation level of zero. If you are extracting a database from an
active server, you should run it at isolation level 3 to ensure that data in the
extracted database is consistent with data on the server. Increasing the
isolation level may result in large numbers of locks being used by the
extraction utility, and may restrict database use by other users.

Output messages to file (–o) Outputs the messages from the extraction
process to a file for later review.

Escape character (–p) The default escape character (\) can be replaced
by another character using this option.

Operate quietly (–q) Display no messages except errors.

Reload filename (–r) The default name for the reload command file is
reload.sql in the current directory You can specify a different file name with
this option.

Output the data unordered (–u) By default the data in each table is
ordered by primary key. Unloads are quicker with the -u switch, but loading
the data into the remote database is slower.

Verbose mode (–v) The name of the table being unloaded and the
number of rows unloaded are displayed. The SELECT statement used is also
displayed.

Use external loads (–x) In the reload script, the default is to use the
LOAD TABLE statement to load the data into the database. If you choose to
use external loads, the Interactive SQL INPUT statement is used instead. The
LOAD TABLE statement is faster than INPUT.
INPUT takes the path of the data files relative to the client, while LOAD
TABLE takes the path relative to the server.

Exclude foreign key definitions (–xf) You can use this if the remote
database contains a subset of the consolidated database schema, and some
foreign key references are not present in the remote database.

160
Chapter 8 Reference

Exclude stored procedure (–xp) Do not extract stored procedures from


the database.

Exclude views (–xv) Do not extract views from the database.

Operate without confirming actions (–y) Without this option, you are
prompted to confirm the replacement of an existing command file.

Adaptive Server Anywhere client synchronization utility


Use the dbmlsync utility to synchronize remote Adaptive Server Anywhere
databases with a consolidated database.
Syntax dbmlsync [ switches ] [ transaction-logs-directory ]

Switch Description
–c "keyword=value;…" Supply database connection parameters.
–d Drop any other connections to the database
whose locks conflict with the articles to be
synchronized.
–dl Display log messages on the console.
–e "keyword=value;…" Specify extended options.
–i file Execute file containing SQL statements
immediately after synchronization.
–k Close window on completion.
–n name Synchronization definition name.
–o logfile Log output messages to this file.
–os size Maximum size of output file.
–ot logfile Truncate file and log output messages to file.
–q Run in minimized window.
–v Verbose operation.

Description Run dbmlsync at the command line to synchronize remote Adaptive Server
Anywhere databases with a consolidated database. dbmlsync uses the
information in the synchronization definition to locate and connect to the
MobiLink synchronization server.

161
Utility programs

The transaction-logs directory is the directory that contains the transaction


log for the Adaptive Server Anywhere client database. You may omit this
parameter only if the working log file has not been truncated and renamed
since you last synchronized, or if the dbmlsync utility is run from the
directory that contains the renamed log files.
You must supply the connection parameters for the consolidated database
using the –c option.
$ For more information about synchronization definitions, see "CREATE
SYNCHRONIZATION DEFINITION statement" on page 197.
Switches –c The connection string must give the MobiLink synchronization server
permission to connect to the consolidated database. This parameter is
required.

–d During synchronization, all tables involved in the synchronization


definition are locked to prevent any other processes from making changes.
Ordinarily, if another process has a lock on one of these tables, the
synchronization is delayed until that process releases its lock. Specifying this
option forces Adaptive Server Anywhere to drop any other connections to
the remote database that hold conflicting locks.

–dl Display messages in the window or on the command line and also in
the log file, if specified.
–e Specify one or more of the following extended options.

162
Chapter 8 Reference

Full Name Short name Default Description


FireTriggers ft ON Fire triggers on download.
Memory mem 1 Mb Memory used for
synchronization.
OfflineDirectory dir NULL Path containing offline
transaction logs.
ScriptsVersion sv default Tells the MobiLink
synchronization server to
use the scripts for the
named schema version,
overriding the setting of
the synchronization
definition option sv.
SendTriggers st OFF Send trigger actions on
upload.
StreamCompression sc MEDIUM Compress upload data
stream: choose LOW,
MEDIUM, or HIGH.
Verbose v OFF Verbose operation.

–i file Immediately upon completing synchronization, and before releasing


the table locks, execute the SQL script contained in the named file. This
option is intended for upgrading applications and making schema changes to
deployed, client databases. Schema changes must be accomplished in this
manner to ensure all changes are in a compatible format.

–k Close window on completion.

–m size Specifies a maximum amount of memory to be used by dbmlsync


for building messages and caching incoming messages, specified in units of
bytes. Use the suffix "k" or "m" to specify units of kilobytes or megabytes,
respectively. The default is 2 Mb.

–n name Name of synchronization definition.

–o Append output to a log file. Default is to send output to the screen.

–os size The size is the maximum file size for logging output messages,
specified in units of bytes. Use the suffix "k" or "m" to specify units of
kilobytes or megabytes, respectively. By default, there is no size limit. The
minimum size limit is 10 kb.

163
Utility programs

Before the dbmlsync utility logs output messages to a file, it checks the
current file size. If the log message will make the file size exceed the
specified size, the dbmlsync utility renames the output file to yymmddnn.dbr,
where nn is a two-digit integer between 00 and 99 and yymmdd represents
the final two digits of the current year, the month, and the day of the month.
This option allows you to manually delete old log files and free up disk
space.

–ot logfile Truncate the log file and then append output messages to it.
When the -o switch is specified, the default is to send output to the screen
and append them to the log file.

–q For Windowing operating systems only, starts dbmlsync with a


minimized window.

–v Verbose output. This switch displays the SQL statements contained in


the messages to the screen. If the -o or -ot switch is used, the messages are
also written to a log file.

Elliptic-curve certificate reader utility


Use the readcert utility to display values within an elliptic-curve certificate
and validate the chain of
Syntax readcert certificate-name
Description When synchronization occurs through a Certicom TLS synchronization
stream, the MobiLink synchronization server sends its certificate to the
client, as well as the certificate of the entity that signed it, and so on up to a
self-signed root. The client checks that the chain is valid and that it trusts the
root certificate in the chain.
This utility scans a non-RSA X509 authentication certificate and displays the
field values. It then checks that the chain of certificates is valid. A validation
error is reported if any of the certificates in the chain have expired, are in the
wrong order, or are missing.

Elliptic-curve certificate generation utility


Use the readcert utility to create a new elliptic-curve certificate.
Syntax gencert [ –c | –s ] [ –r ]

164
Chapter 8 Reference

Switch Description
–c Generate a certificate authority certificate.
–r Generate a self-signed root certificate.
–s Generate a server identity certificate.

Description This utility creates a new X509 certificate. When first started, it generates an
elliptic-curve key pair. It then requests values for the distinguished fields.
These fields include the country, state or province, locality, organization,
organizational unit, and common name, the serial number, and an expiry
date. It then requests the file name of a certificate that is to sign the new
certificate.
If no certificate name is supplied, the new certificate becomes a root
certificate. If a certificate file name is supplied, gencert reads and validates
the certificate chain and requests the name of the file that contains the
signer’s private key. It then requests the password for that private key.
The then utility requests the password that is to protect the new private key.
This utility writes three different types of files. One file contains only the
new certificate. Another contains only the encrypted private key, and a third
file contains both the certificate and the encrypted private key.
Often, not all three files are needed. For example, if the certificate is to be a
certificate authority, used to sign other certificates, the file that contains only
the certificates is distributed as a trusted root certificate to clients. The file
containing the encrypted private key is stored securely. In this case, security
is improved by storing the private key and the certificate separately, so the
third file is not generated.
If, instead, the certificate is to identify a server, the encrypted private key
should be stored with the certificate, so the utility writes only the file that
contains both pieces of information.
If the signing certificate is not a root certificate, but is instead part of a chain,
gencert reads and validates the entire chain before issuing the new
certificate.
When generating a server identity certificate, the entire chain is always
saved. Otherwise, saving the entire chain is optional.
Switches –c Generate a certificate authority certificate. A certificate authority can be
used to sign other certificates. By default, generated certificates cannot be
used as certificate authorities.

165
Utility programs

–r Generate a root certificate. A root certificate is signed only by itself. The


default is to prompt for the name of a file that contains the certificate that is
to sign the new, generated certificate.

–s Generate a server identity certificate, used to identify a MobiLink


synchronization server, rather than a client. A server identity certificate
cannot be a certificate authority, so this switch is incompatible with the -c
switch. The default is to generate a client certificate.

166
Chapter 8 Reference

MobiLink system tables


The tables used for MobiLink are shown below. Arrows indicate foreign key
relations between tables: the arrow leads from the foreign table to the
primary table.
These tables are always present in Adaptive Server Anywhere databases and
are owned by dbo. They can also be installed in database systems sold by
other vendors, for use when the alternate database system is to be used as a
MobiLink consolidated database.

ml_table ml_user
table_id <pk> integer user_id <pk> integer
name <ak> varchar(128) name varchar(128)
commit_state integer

ml_scripts_modified
table_id = table_id last_modified datetime

ml_table_script
version_id <pk,fk> integer version_id = version_id
table_id <pk,fk> integer
event <pk> varchar(128)
script_id <fk> integer
ml_script_version
script_id = script_id version_id <pk> integer
name varchar(128)
description text
ml_script
script_id <pk> integer
script text version_id = version_id

ml_connection_script
version_id <pk,fk> integer
script_id = script_id event <pk> varchar(128)
script_id <fk> integer

* Under IBM DB2, the table names ml_scripts_modifie and ml_connection_scri are used,
due to the 18 character limit.

167
Data-type conversions

Data-type conversions
Conversion of data types must take place when a MobiLink synchronization
server communicates with a consolidated database that was not made with
Adaptive Server Anywhere. The following tables identify these mappings.

Sybase Adaptive Server Enterprise


The following table identifies how MobiLink data types are mapped to
Adaptive Server Enterprise data types.

MobiLink data type Sybase ASE data type


bit bit
tinyint tinyint
smallint smallint
int int
integer integer
decimal [defaults p=30, s=6] numeric(30,6)
decimal(128,128) not supported
numeric [defaults p=30 s=6] numeric(30,6)
numeric(128,128) not supported
float real
real real
double float
smallmoney numeric(10,4)
money numeric(19,4)
date datetime
time datetime
timestamp datetime
smalldatetime datetime
datetime datetime
char(n) varchar(n)
character(n) varchar(n)
varchar(n) varchar(n)

168
Chapter 8 Reference

MobiLink data type Sybase ASE data type


character varying(n) varchar(n)
long varchar text
text text
binary(n) binary(n)
long binary image
image image
bigint numeric(20,0)

IBM DB2
The following table identifies how MobiLink data types are mapped to
IBM DB2 data types.

MobiLink data type IBM DB2 data type


Bit smallint
Tinyint smallint
Smallint smallint
Int int
Integer int
Bigint decimal(20,0)
char(1–254) varchar(n)
char(255–4000) varchar(n)
char(4001–32767) long varchar
Character(1–254) varchar(n)
Character(255–4000) varchar(n)
Character(4001-32767) long varchar
varchar(1–4000) varchar(n)
varchar(4001–32767) long varchar
Character varying(1–4000) varchar(n)
Character varying(4001–32767) long varchar or CLOB(n)
long varchar long varchar or CLOB(n)
text long varchar

169
Data-type conversions

MobiLink data type IBM DB2 data type


binary(1–4000) varchar for bit data or BLOB(n)
binary(4001–32767) long varchar for bit data or BLOB(n)
long binary long varchar for bit data or BLOB(n)
image long varchar for bit data or BLOB(n)
decimal [defaults p=30, s=6] decimal(30,6)
numeric [defaults p=30 s=6] decimal(30,6)
decimal(128, 128) NOT SUPPORTED
numeric(128, 128) NOT SUPPORTED
real real
float float
double float
smallmoney decimal(10,4)
money decimal(19,4)
date date
time time
smalldatetime timestamp
datetime timestamp
timestamp timestamp

Oracle
The following table identifies how MobiLink data types are mapped to
Oracle data types.

MobiLink data type Oracle data type


bit number(1,0)
tinyint number(3,0)
smallint number(5,0)
int number(11,0)
bigint number(20,0)
decimal(prec, scale) number(prec, scale)
numeric(prec, scale) number(prec, scale)

170
Chapter 8 Reference

MobiLink data type Oracle data type


float float
real real
smallmoney numeric(13,4)
money number(19,4)
date date
time date
timestamp date
smalldatetime date
datetime date
char(n) if (n > 255) long else varchar(n), or CLOB(n)
varchar(n) if (n > 2000) long else varchar(n), or CLOB(n)
longchar long or CLOB(n)
binary(n) if (n > 255) long raw else raw(n), or BLOB(n)
varbinary(n) if (n > 255) long raw else raw(n), or BLOB(n)
longbinary long raw

Microsoft SQL Server


The following table identifies how MobiLink data types are mapped to
Microsoft SQL Server data types.

MobiLink data type Microsoft SQL Server data type


bit bit
tinyint tinyint
smallint smallint
int int
bigint numeric(20,0)
decimal [defaults p=30, s=6] decimal(prec, scale)
numeric [defaults p=30 s=6] numeric(prec, scale)
float if (prec) float(prec) else float
real real
smallmoney smallmoney

171
Data-type conversions

MobiLink data type Microsoft SQL Server data type


money money
date datetime
time datetime
timestamp datetime
smalldatetime datetime
datetime datetime
char(n) if (length > 255) text else varchar(length)
character(n) varchar(n)
varchar(n) if (length > 255) text else varchar(length)
longchar text
binary(n) if (length > 255) image else
binary(length)
long binary image
double float

172
Chapter 8 Reference

Scripts
This section lists the scripts in alphabetical order. Arguments are optional.

begin_connection connection script


Function To process any statements at the time the MobiLink synchronization server
connects to the consolidated database server.
Arguments None.
Default action No action.
See also "end_connection connection script" on page 179
Description The MobiLink synchronization server executes this script upon opening each
worker-thread connection to the consolidated database server. The MobiLink
synchronization server typically opens one or more connections when it is
launched. When an application forms or re-forms a connection with the
MobiLink synchronization server, the MobiLink synchronization server, in
turn, temporarily allocates one connection with the database server for the
duration of that synchronization.

begin_download connection script


Function To process any statements just before the MobiLink synchronization server
commences preparing the download data stream.
Arguments user_name varchar(128)
Default action No action.
See also "end_download connection script" on page 179
Description The MobiLink synchronization server executes this script as the first step in
the processing of downloaded information. Download information is
processed in a single transaction. The execution of this script is the first
action in this transaction.

begin_download table script


Function To process statements related to a specific table just before the MobiLink
synchronization server begins preparing the download stream of inserts,
updates, and deletions.

173
Scripts

Arguments user_name varchar(128), table varchar(128)


Default action No action.
See also "end_download table script" on page 180
Description The MobiLink synchronization server executes this script as the first step in
the preparing download information. The download information is prepared
in a separate transaction. The execution of this script is the first table-specific
action in this transaction.
You can have one begin_download script for each table in the remote
database.

begin_download_deletes table script


Function To process statements related to a specific table just before preparing a list of
rows to be deleted from the specified table in the remote database.
Arguments user_name varchar(128), table varchar(128)
Default action No action.
See also "end_download_deletes table script" on page 180
"begin_download connection script" on page 173
Description This script is executed immediately before preparing a list of rows to be
deleted from the named table in the remote database.
You can have one begin_download_deletes script for each table in the
remote database.

begin_download_rows table script


Function To process statements related to a specific table just before preparing a list of
rows to be inserted or updated in the specified table in the remote database.
Arguments user_name varchar(128), table varchar(128)
Default action No action.
See also "end_download_rows table script" on page 180
"begin_download connection script" on page 173
Description This script is executed immediately before preparing the stream of rows to be
inserted or updated in the named table in the remote database.

174
Chapter 8 Reference

You can have one begin_download_rows script for each table in the remote
database.

begin_synchronization connection script


Function To process any statements at the time an application connects to the
MobiLink synchronization server in preparation for the synchronization
process.
Arguments user_name varchar(128)
Default action No action.
See also "end_synchronization connection script" on page 181
"begin_synchronization table script" on page 175
Description The MobiLink synchronization server executes this script immediatly after
an application preparing to synchronize has formed a connection with the
MobiLink synchronization server.
This script is executed within a separate transaction before the upload
transaction. It is useful for maintaining statistics.

begin_synchronization table script


Function To process statements related to a specific table at the time an application
connects to the MobiLink synchronization server in preparation for the
synchronization process.
Arguments user_name varchar(128), table varchar(128)
Default action No action.
See also "end_synchronization table script" on page 181
"begin_synchronization connection script" on page 175
Description The MobiLink synchronization server executes this script after an application
preparing to synchronize has formed a connection with the MobiLink
synchronization server, and after the connection level script of the same
name.
You can have one begin_synchronization script for each table in the remote
database.

175
Scripts

begin_upload connection script


Function To process any statements just before the MobiLink synchronization server
commences processing the stream of uploaded inserts, updates, and
deletions.
Arguments user_name varchar(128)
Default action No action.
See also "end_upload connection script" on page 182
"begin_upload table script" on page 176
Description The MobiLink synchronization server executes this script as the first step in
the processing of uploaded information. Upload information is processed in a
single transaction. The execution of this script is the first action in this
transaction.

begin_upload table script


Function To process statements related to a specific table just before the MobiLink
synchronization server commences processing the stream of uploaded
inserts, updates, and deletions.
Arguments user_name varchar(128), table varchar(128)
Default action No action.
See also "end_upload table script" on page 182
"begin_upload connection script" on page 176
Description The MobiLink synchronization server executes this script as the first step in
the processing of uploaded information. Upload information is processed in a
separate transaction. The execution of this script is the first table-specific
action in this transaction.
You can have one begin_upload script for each table in the remote database.

begin_upload_deletes table script


Function To process statements related to a specific table just before deleting rows that
were deleted from the specified table in the remote database.
Arguments user_name varchar(128), table varchar(128)
Default action No action.
See also "end_upload_deletes table script" on page 183

176
Chapter 8 Reference

Description Uploaded information can require deleting rows in the consolidated database.
This script is run immediately before applying the changes that result from
rows deleted in the remote table named in the second argument.
You can have one begin_upload_deletes script for each table in the remote
database.

begin_upload_rows table script


Function To process statements related to a specific table just before applying inserts
and updates from the specified table in the remote database.
Arguments user_name varchar(128), table varchar(128)
Default action No action.
See also "end_upload_rows table script" on page 183
Description Uploaded information can require inserting or updating rows in the
consolidated database. This script is run immediately prior to applying the
changes that result from modifications to the remote table named in the
second argument.
You can have one begin_upload_rows script for each table in the remote
database.

download_cursor cursor script


Function Define a cursor to select rows that are to be downloaded and inserted or
updated in the remote database.
Arguments user_name varchar(128)
Default action No action, but the UltraLite analyzer generates a SELECT statement based
on your reference database that you can use to get started. For each table in
the UltraLite database, the UltraLite generator adds two scripts to the
reference database. The example_download_cursor and the
example_upload_cursor scripts are useful starting points when writing
scripts.
See also "upload_cursor cursor script" on page 188
"download_delete_cursor cursor script" on page 178
Description The MobiLink synchronization server opens a read-only cursor with which
to prepare a list of rows to download to the remote database. This script
should contain a suitable SELECT statement.

177
Scripts

Unlike the upload cursors, the only argument is the user name. You can use
this value if you choose by placing a question mark in your SQL statement.
Unlike in the upload_cursor, the use of a question mark is optional.
You can have one download_cursor script for each table in the remote
database.
Example The following SELECT statement defines a download cursor that downloads
orders that have not yet been approved.
SELECT o.order_id, o.cust_id, o.prod_id, o.emp_id,
o.disc, o.quant, o.notes, o.status
FROM ULOrder o, ULEmpCust ec
WHERE o.cust_id = ec.cust_id
AND ec.emp_id = @EmployeeID
AND ( o.last_modified > @LastDownload
OR ec.last_modified > @LastDownload )
AND ( o.status IS NULL
OR o.status != ’Approved’ )
AND ( ec.action IS NULL )

download_delete_cursor cursor script


Function Define a cursor to select rows that are to be deleted in the remote database.
Arguments user_name varchar(128)
Default action No action.
See also "upload_cursor cursor script" on page 188
"download_cursor cursor script" on page 177
Description The MobiLink synchronization server opens a read-only cursor with which
to prepare a list of rows to download and insert or update in the remote
database. This script must contain a SELECT statement that returns the
primary key values of the rows to be deleted from the remote table.
Unlike the upload cursors, the only argument is the user name. You can use
this value if you choose by placing a question mark in your SQL statement.
Unlike in the upload_cursor, the use of a question mark is optional.
You can have one download_delete_cursor script for each table in the remote
database.
Examples The following SELECT statement defines a download cursor that deletes
approved orders in the remote database. The order id column is the only
column in the primary key of this table, so only this column is selected.
SELECT order_id
FROM ULOrder
WHERE emp_id = ?

178
Chapter 8 Reference

AND status = ’Approved’


AND last_modified > @LastDownload
For compatibility with older versions, the following SELECT statement also
defines a download cursor that deletes approved orders in the remote
database. This cursor has the same effect, but is less efficient because the
database engine must retrieve the extra columns from the database. The extra
columns are not included in the download stream. The MobiLink
synchronization server simply discards them.
SELECT order_id, cust_id, prod_id, disc,
quant, notes, status
FROM ULOrder
WHERE emp_id = ?
AND status = ’Approved’
AND last_modified > @LastDownload

end_connection connection script


Function To process any statements just before the MobiLink synchronization server
closes a connection with the consolidated database server, typically in
preparation to shut down.
This script is normally used to complete any actions started by the
begin_connection script and free any resources acquired by it.
Arguments None.
Default action No action.
See also "begin_connection connection script" on page 173
Description You can use the end_connection script to perform an action of your choice
just prior to closing of a connection between the MobiLink synchronization
server and the consolidated database server.

end_download connection script


Function To process any statements just before the MobiLink synchronization server
concludes preparation of the download data stream.
Arguments user_name varchar(128)
Default action No action.
See also "begin_download connection script" on page 173

179
Scripts

Description The MobiLink synchronization server executes this script after all rows have
been downloaded and confirmation of receipt has been received. Download
information is processed in a single transaction. The execution of this script
is the last action in this transaction.

end_download table script


Function To process statements related to a specific table just after the MobiLink
synchronization server concludes preparing the stream of downloaded
inserts, updates, and deletions.
Arguments user_name varchar(128), table varchar(128)
Default action No action.
See also "begin_download table script" on page 173
Description The MobiLink synchronization server executes this script after all rows have
been downloaded and confirmation of receipt has been received. The
download information is prepared in a separate transaction. The execution of
this script is the last table-specific action in this transaction.
You can have one end_download script for each table in the remote database.

end_download_deletes table script


Function To process statements related to a specific table just after preparing a list of
rows to be deleted from the specified table in the remote database.
Arguments user_name varchar(128), table varchar(128)
Default action No action.
See also "begin_download_deletes table script" on page 174
"end_download connection script" on page 179
Description This script is executed immediately after preparing a list of rows to be
deleted from the named table in the remote database.
You can have one end_download_deletes script for each table in the remote
database.

end_download_rows table script


Function To process statements related to a specific table just after preparing a list of
rows to be inserted or updated in the specified table in the remote database.
180
Chapter 8 Reference

Arguments user_name varchar(128), table varchar(128)


Default action No action.
See also "begin_download_rows table script" on page 174
"end_download connection script" on page 179
Description This script is executed immediately after preparing the stream of rows to be
inserted or updated in the named table in the remote database.
You can have one end_download_rows script for each table in the remote
database.

end_synchronization connection script


Function To process any statements at the time an application disconnects from the
MobiLink synchronization server upon completion of the synchronization
process.
Arguments user_name varchar(128)
Default action No action.
See also "begin_synchronization connection script" on page 175
"end_synchronization table script" on page 181
Description The MobiLink synchronization server executes this script after
synchronization is complete and the MobiLink client has returned
confirmation of receipt of the download stream.
This script is executed within a separate transaction after the download
transaction. It is useful for maintaining statistics.

end_synchronization table script


Function To process statements related to a specific table at the time an application
disconnects from the MobiLink synchronization server upon completion of
the synchronization process.
Arguments user_name varchar(128), table varchar(128)
Default action No action.
See also "begin_synchronization table script" on page 175
"end_synchronization connection script" on page 181

181
Scripts

Description The MobiLink synchronization server executes this script after an application
has synchronized and is about to disconnect from the MobiLink
synchronization server, and before the connection level script of the same
name.
You can have one end_synchronization script for each table in the remote
database.

end_upload connection script


Function To process any statements just after the MobiLink synchronization server
concludes processing the stream of uploaded inserts, updates, and deletions.
Arguments user_name varchar(128)
Default action No action.
See also "begin_upload connection script" on page 176
"end_upload table script" on page 182
Description The MobiLink synchronization server executes this script as the last step in
the processing of uploaded information. Upload information is processed in a
single transaction. The execution of this script is the last action in this
transaction.

end_upload table script


Function To process statements related to a specific table just after the MobiLink
synchronization server concludes processing the stream of uploaded inserts,
updates, and deletions.
Arguments user_name varchar(128), table varchar(128)
Default action No action.
See also "begin_upload table script" on page 176
"end_upload connection script" on page 182
Description The MobiLink synchronization server executes this script as the last step in
the processing of uploaded information. Upload information is processed in a
separate transaction. The execution of this script is the last table-specific
action in this transaction.
You can have one end_upload script for each table in the remote database.

182
Chapter 8 Reference

end_upload_deletes table script


Function To process statements related to a specific table just after applying deletes
from the specified table in the remote database.
Arguments user_name varchar(128), table varchar(128)
Default action No action.
See also "begin_upload_deletes table script" on page 176
Description Uploaded information can require deleting rows in the consolidated database.
This script is run immediately after applying the changes that result from
rows deleted in the remote table named in the second argument.
You can have one end_upload_deletes script for each table in the remote
database.

end_upload_rows table script


Function To process statements related to a specific table just after applying inserts
and updates from the specified table in the remote database.
Arguments user_name varchar(128), table varchar(128)
Default action No action.
See also "begin_upload_rows table script" on page 177
Description Uploaded information can require inserting or updating rows in the
consolidated database. This script is run immediately after applying the
changes that result from modifications to the remote table named in the
second argument.
You can have one end_upload_rows script for each table in the remote
database.

handle_error connection script


Function Executed whenever the MobiLink synchronization server encounters a SQL
error.
Arguments error_code int, error_message text, user_name varchar(128),
table varchar(128)
Default action The action code is one of the following values:
♦ 1000 Skip the current row and continue processing.

183
Scripts

♦ 3000 Rollback the current transaction and cancel the current


synchronization. This is the default action code, and is used when no
handle_error script is defined or this script causes an error.
♦ 4000 Rollback the current transaction, cancel the synchronization, and
shut down the server.

The MobiLink synchronization server selects a default action code, which


depends on the severity of the error.
See also "report_error connection script" on page 187
Description The MobiLink synchronization server executes this script whenever it
encounters an error during the synchronization process. The error codes
allow you to identify the nature of the error. If the error happened as part of
synchronization, the user name is supplied. Otherwise, this value is NULL.
If the error happened while manipulating a particular table, the table name is
supplied. Otherwise, this value is NULL. The table name is the name of a
table in the remote application. This name may or may not have a direct
counterpart in the consolidated database, depending upon the design of the
synchronization system.
The action code tells the MobiLink synchronization server what to do next.
Before it calls this script, the MobiLink synchronization server sets the
action code to a default value, which depends upon the severity of the error.
Your script may modify this value. Your script must return an action code.

new_row_cursor cursor script


Function Defines the insert cursor that the server uses to insert the new values of rows
that were updated in the remote database, but conflict with values presently
in the consolidated database.
Arguments user_name varchar(128)
Default action No action.
See also "upload_cursor cursor script" on page 188
"old_row_cursor cursor script" on page 185
"Handling conflicts" on page 109
Description When a row is updated on a remote database, the MobiLink client saves a
copy of the original values. The client sends both old and new values to the
MobiLink synchronization server.

184
Chapter 8 Reference

When the MobiLink synchronization server receives an updated row, it


compares the orginal values with the present values in the consolidated
database, using the upload_cursor. If the old uploaded values do not match
the current value in the consolidated database, the row conflicts. Instead of
updating the row, the MobiLink synchronization server inserts both old and
new values into the consolidated database using the old_row_cursor and the
new_row_cursor, respectively.
The MobiLink synchronization server uses a cursor to insert the new
uploaded values from conflicting rows into the consolidated database. This
script contains the SELECT statement used to define this cursor.
It is common practice to use temporary tables to store the old and new
versions of conflicting rows. You can create these temporary tables in an
earlier script.
You can have one new_row_cursor script for each table in the remote
database.
Normally, the columns in the select list must match those in the remote table
in both order and type. However, the MobiLink synchronization server
permits you to add one extra column. If you do so, the MobiLink
synchronization server automatically inserts the user name into the first
column, then proceeds to insert the old row values using the remaining
columns, as usual.
Examples ♦ The following SELECT statement defines a new_row_cursor script
suited to the CustDB sample application.
SELECT order_id, cust_id, prod_id, emp_id, disc,
quant, notes, status
FROM ULNewOrder
The primary key of the ULOrder table is order_id.
♦ The following SELECT statement could instead be used for the same
remote table. This variation includes the permitted one extra row. The
MobiLink synchronization server automatically stores the user name in
the first column.
SELECT user_name, order_id, cust_id, prod_id,
emp_id, disc, quant, notes, status
FROM ULNewOrder

old_row_cursor cursor script


Function Defines the cursor that the server uses to insert the old values of rows that
were updated in the remote database, but conflict with values presently in the
consolidated database.

185
Scripts

Arguments user_name varchar(128)


Default action No action.
See also "upload_cursor cursor script" on page 188
"new_row_cursor cursor script" on page 184
Description When a row is updated on a remote database, the MobiLink client saves a
copy of the original values. The client sends both old and new values to the
MobiLink synchronization server.
When the MobiLink synchronization server receives an updated row, it
compares the original values with the present values in the consolidated
database, using the upload_cursor. If the old uploaded values do not match
the current values in the consolidated database, the row conflicts. Instead of
updating the row, the MobiLink synchronization server inserts both old and
new values into the consolidated database using the old_row_cursor and the
new_row_cursor, respectively.
It is common practice to use temporary tables to store the old and new
verions of conflicting rows. You can create these temporary tables in an
earlier script.
The MobiLink synchronization server uses a cursor to insert the old uploaded
values from conflicting rows into the consolidated database. This script
contains the SELECT statement used to define this cursor.
You can have one old_row_cursor script for each table in the remote
database.
Normally, the columns in the select list must match those in the remote table
in both order and type. However, the MobiLink synchronization server
permits you to add one extra column. If you do so, the MobiLink
synchronization server automatically inserts the user name into the first
column, then proceeds to insert the old row values using the remaining
columns, as usual.
Examples ♦ The following SELECT statement defines a old_row_cursor script
suited to the CustDB sample application.
SELECT order_id, cust_id, prod_id, emp_id, disc,
quant, notes, status
FROM ULOldOrder
The primary key of the ULOrder table is order_id.
♦ The following SELECT statement could instead be used for the same
remote table. This variation includes the permitted one extra row. The
MobiLink synchronization server automatically stores the user name in
the first column.

186
Chapter 8 Reference

SELECT user_name, order_id, cust_id, prod_id,


emp_id, disc, quant, notes, status
FROM ULOldOrder

report_error connection script


Function Executed whenever the MobiLink synchronization server encounters a SQL
error, immediately following the handle_error script, whether or not it is
defined.
Arguments action_code int, error_code int, error_message text, user_name varchar(128),
table varchar(128)
Default action None.
See also "handle_error connection script" on page 183
Description The MobiLink synchronization server executes this script whenever it
encounters an error during the synchronization process and immediately after
executing the handle_error script, whether or not it is defined. The error
codes allow you to identify the nature of the error. The action code is the
value returned by handle_error, or if handle_error is undefined, the default
action code selected by the MobiLink synchronization server. If the error
happened as part of synchronization, the user name is supplied. Otherwise,
this value is NULL.
If the error happened while manipulating a particular table, the table name is
supplied. Otherwise, this value is NULL. The table name is the name of a
table in the remote application. This name may or may not have a direct
counterpart in the consolidated database, depending upon the design of the
synchronization system.
This script allows you to log errors and to record the actions selected by the
handle_error script. This script is always executed immediately following
the completion of handle_error. It is always executed in a separate
transaction. All changes made by the script are automatically committed.

resolve_conflict table script


Function Defines a process for resolving a conflict.
Arguments user_name varchar(128), table varchar(128)
Default action No action.
See also "old_row_cursor cursor script" on page 185

187
Scripts

"new_row_cursor cursor script" on page 184


"end_upload_rows table script" on page 183
Description When a row is updated on a remote database, the MobiLink client saves a
copy of the original values. The client sends both old and new values to the
MobiLink synchronization server.
When the MobiLink synchronization server receives an updated row, it
compares the orginal values with the present values in the consolidated
database, using the upload_cursor. If the old uploaded values do not match
the current values in the consolidated database, the row conflicts. Instead of
updating the row, the MobiLink synchronization server inserts both old and
new values into the consolidated database using the old_row_cursor and the
new_row_cursor, respectively.
Once the values have been inserted, the MobiLink synchronization server
executes this script. It provides the opportunity to resolve the conflict. You
can implement any scheme of your choosing.
This script is executed once per conflict.
Alternatively, instead of defining the resolve_conflict script, you can resolve
conflicts in a set-oriented fashion by putting conflict-resolution logic in your
end_upload_rows script.
You can have one resolve_conflict script for each table in the remote
database.

upload_cursor cursor script


Function Defines the cursor that the server uses to insert, update, or delete rows during
processing of the upload stream.
Arguments primary_key_1, primary_key_2, …, primary_key_n
Default action No action, but the UltraLite analyzer generates a SELECT statement based
on your reference database that you can use to get started. For each table in
the UltraLite reference database, the UltraLite generator adds two scripts to
the reference database. The example_download_cursor and the
example_upload_cursor scripts are useful starting points when writing
scripts.
See also "download_cursor cursor script" on page 177
Description The MobiLink synchronization server opens a cursor with which to insert,
update, or delete rows in the consolidated database based on rows uploaded
from a remote application. This script should contain a suitable SELECT
statement or call a stored procedure that contains a suitable SELECT
statement.

188
Chapter 8 Reference

The arguments are the values of each column included in the primary key of
the corresponding remote table. You must use these in a WHERE clause, so
that the synchronization can identify a unique row in the cursor based on
these values. The type and order of the arguments is as defined in the
example_upload_cursor script. This order is the same as that in the
corresponding table definition in the remote database, which in turn may
have been copied from your reference database.
You can have one upload_cursor script for each table in the remote database.
Example The following SELECT statement defines the upload cursor in the CustDB
sample application.
SELECT cust_id, cust_name
FROM ULCustomer
WHERE cust_id = ?
The primary key of the ULCustomer table in the CustDB sample application
is the column cust_id. If the corresponding table in the consolidated database
is, instead, named Customer, then change the above statement as follows.
SELECT cust_id, cust_name
FROM Customer
WHERE cust_id = ?

189
Stored procedures

Stored procedures
The script that adds the MobiLink tables to the consolidated database
automatically defines the following stored procedures. They may be used to
facilitate the process of adding synchronization scripts to the consolidated
database.

ml_add_connection_script
Function Use this stored procedure to facilitate the task of adding connection scripts to
the consolidated database.
Arguments @version char(128),
@event char(128),
@script text
See also "ml_add_table_script" on page 190
Description The script is inserted into the ml_script table and the appropriate references
are defined to associate this script with event @event and script version
@version. If the version name is new, it is automatically inserted into the
ml_version table.
Example call ml_add_connection_script( ’version_1’,
’begin_synchronization’,
’set @EmployeeID = ?’ )

ml_add_table_script
Function Use this stored procedure to facilitate the task of adding table scripts to the
consolidated database.
Arguments @version char(128),
@name char(128),
@event char(128),
@script text
See also "ml_add_connection_script" on page 190
Description The script is inserted into the ml_script table and the appropriate references
are defined to associate this script with table @name, event @event, and
script version @version. If the version name is new, it is automatically
inserted into the ml_version table.
Example call ml_add_table_script( ’version_1’,
’ULCustomer’,

190
Chapter 8 Reference

’upload_cursor’,
’SELECT cust_id, cust_name
FROM ULCustomer WHERE cust_id = ?’ )

191
SQL statements

SQL statements
The following statements are required to synchronize Adaptive Server
Anywhere applications.

ALTER SYNCHRONIZATION DEFINITION statement


Function Use this statement to alter a synchronization definition.
Syntax ALTER SYNCHRONIZATION DEFINITION SyncDefName
[ SITE SyncSiteName, ]
[ TYPE SyncType, ]
[ ADDRESS MLServerAddress, ]
[ ADD OPTION parameter=value, … ]
[ MODIFY OPTION parameter=value, … ]
[ DELETE OPTION parameter, …
| DELETE ALL OPTION, ]
[ RENAME NewSyncDefName, ]
[ ADD TABLE article-description, … ]
[ MODIFY TABLE article-description, … ]
[ DELETE TABLE table-name, … ]
article-description:
table-name [ ( column-name, ... ) ]
[ WHERE search-condition ]
value:
’string’ | integer | "SQL variable name"
Permissions Must have DBA authority. Requires exclusive access to all tables referred to
in the statement.
Side effects Automatic commit
See also "CREATE SYNCHRONIZATION DEFINITION statement" on page 197
"DROP SYNCHRONIZATION DEFINITION statement" on page 206
Description Synchronization definitions are created in Adaptive Server Anywhere
database that are to serve as a MobiLink clients. Each definition specifies the
site name that uniquely identifies that logical MobiLink client within the
MobiLink setup. In addition, each site specifies how to contact the MobiLink
synchronization server and which data in the remote database is to be
synchronized with the consolidated database.
Use the ALTER SYNCHRONIZATION DEFINITION statement to alter a
synchronization definition.
For example, if you wish to make changes to the options and set memory to
3 Mb, you can alter the synchronization definition as follows:

192
Chapter 8 Reference

ALTER SYNCHRONIZATION DEFINITION mysharedtables


OPTION memory=’3m’
Parameters Using the following clauses, you can alter the settings in your
synchronization definition.

SITE clause The name that uniquely identifies this remote site within your
MobiLink setup.

TYPE clause The TYPE clause specifies the method of synchronization.


The default value is TCP/IP. You may also choose to use HTTP.

ADDRESS clause The ADDRESS clause specifies the location of the


MobiLink synchronization server.
$ For a complete list of the available parameters, see "CREATE
SYNCHRONIZATION DEFINITION statement" on page 197.

ADD OPTION, MODIFY OPTION, DELETE OPTION AND DELETE ALL


OPTION clause These clauses allow you to add, modify, delete or delete
all options. You may specify only one parameter in each clause.
The values for each option cannot contain the characters "=" or "," or ";".
For a list of available options, see "CREATE SYNCHRONIZATION
DEFINITION statement" on page 197.

Enter options carefully


The database engine will accept any option that you enter without
checking for its validity. Therefore, if you misspell an option, the engine
will not detect the error and no error message will be given until you run
the dbmlsync command to perform synchronization.

RENAME clause Use this clause to rename your synchronization


definition.

ADD TABLE, MODIFY TABLE AND DELETE TABLE clause You have
previously specified, in your CREATE SYNCHRONIZATION
DEFINITION statement, the contents to be uploaded to the consolidated
database. Use these clauses to make changes to the specification.
Compatibility ♦ Sybase Adaptive Server Anywhere version 7.0.
Example ♦ Alter the mysharedtables synchronization definition. Switch to a
different remote site and set different options. In addition, the table
Books is also uploaded to the consolidated database and only two
columns of the People table are uploaded to the consolidated database.
ALTER SYNCHRONIZATION DEFINITION mysharedtables
SITE ’new_sync_site’,

193
SQL statements

ADD OPTION verbose=’on’,


MODIFY OPTION memory=’3m’,
ADD TABLE Books,
MODIFY TABLE People(fname, lname);

ALTER SYNCHRONIZATION SITE statement


Function Use this statement to alter a site within a MobiLink reference database, to be
used when extracting remote Adaptive Server Anywhere client databases
with the mlxtract command-line utility.
Syntax ALTER SYNCHRONIZATION SITE SyncSiteName
[ RENAME NewSyncSiteName, ]
[ TYPE SyncType, ]
[ ADDRESS MLServerAddress, ]
[ ADD OPTION parameter=value, … ]
[ MODIFY OPTION parameter=value, … ]
[ DELETE OPTION parameter, …
| DELETE ALL OPTION ]
Parameters value:
’string’ | integer | "variable name"
Permissions Must have DBA authority.
Side effects Automatic commit
See also "CREATE SYNCHRONIZATION SITE statement" on page 202
"DROP SYNCHRONIZATION SITE statement" on page 206
Description Synchronization templates and synchronization sites are used only when
creating remote Adaptive Server Anywhere databases by means of extracting
them from a MobiLink reference database.
Each remote database is created from a synchronization site, stored within
the reference database. Each synchronization site is based upon a single
synchronization template, although many sites can use a single template.
Use the ALTER SYNCHRONIZATION SITE statement to modify the
properties of a synchronization site.
Parameters Using the following clauses, you can alter the settings in your
synchronization definition.

SITE clause The name that uniquely identifies this remote site within your
MobiLink setup.

TYPE clause The TYPE clause specifies the method of synchronization.


The default value is tcpip. You may also choose to use http.

194
Chapter 8 Reference

ADDRESS clause The ADDRESS clause specifies the location of the


MobiLink synchronization server.
$ For a complete list of the available parameters, see "CREATE
SYNCHRONIZATION DEFINITION statement" on page 197.

ADD OPTION, MODIFY OPTION, DELETE OPTION AND DELETE ALL


OPTION clause These clauses allow you to add, modify, delete or delete
all options. You may specify only one parameter in each clause.
The values for each option cannot contain the characters "=" or "," or ";".
For a list of available options, see "CREATE SYNCHRONIZATION SITE
statement" on page 202.
Compatibility ♦ Sybase Adaptive Server Anywhere version 7.0.
Example ♦ Deploy mytemplate to a different remote site and set different options
from the ones in the template.
ALTER SYNCHRONIZATION SITE USING mytemplate
SITE ’new_sync_site’,
ADD OPTION verbose=’on’
MODIFY OPTION memory=’3m’;

ALTER SYNCHRONIZATION TEMPLATE statement


Function Use this statement to alter a template within a MobiLink reference database,
to be used when extracting remote Adaptive Server Anywhere client
databases with the mlxtract command-line utility.
Syntax ALTER SYNCHRONIZATION TEMPLATE SyncTemplateName,
[ TYPE SyncType, ]
[ ADDRESS MLServerAddress, ]
[ ADD OPTION parameter=value, … ]
[ MODIFY OPTION parameter=value, … ]
[ DELETE OPTION parameter, …
| DELETE ALL OPTION, ]
[ RENAME NewSyncDefName, ]
[ ADD TABLE article-description, … ]
[ MODIFY TABLE article-description, … ]
[ DELETE TABLE table-name, … ]
article-description:
table-name [ ( column-name, ... ) ]
[ WHERE search-condition ]
value:
’string’ | integer | "SQL variable name"

195
SQL statements

Permissions Must have DBA authority. Requires exclusive access to all tables referred to
in the statement.
Side effects Automatic commit
See also "CREATE SYNCHRONIZATION TEMPLATE statement" on page 204
"DROP SYNCHRONIZATION TEMPLATE statement" on page 207
Description Synchronization templates and synchronization sites are used only when
creating remote Adaptive Server Anywhere databases by means of extracting
them from a MobiLink reference database.
Each remote database is created from a synchronization site, stored within
the reference database. Each synchronization site is based upon a single
synchronization template, although many sites can use a single template.
Use the ALTER SYNCHRONIZATION TEMPLATE statement to modify
the properties of a synchronization template.
Parameters Using the following clauses, you can alter the configurations in your
synchronization definition.

TYPE clause The TYPE clause specifies the method of synchronization.


The default value is tcpip. You may also choose to use http.

ADDRESS clause The ADDRESS clause specifies the location of the


MobiLink synchronization server.
$ For a complete list of the available parameters, see "CREATE
SYNCHRONIZATION DEFINITION statement" on page 197.

ADD OPTION, MODIFY OPTION, DELETE OPTION AND DELETE ALL


OPTION clause These clauses allow you to add, modify, delete or delete
all options. You may specify only one parameter in each clause.
The values for each option cannot contain the characters "=" or "," or ";".
For a list of available options, see "CREATE SYNCHRONIZATION
TEMPLATE statement" on page 204.

RENAME clause Use this clause to rename your synchronization


definition.

ADD TABLE, MODIFY TABLE AND DELETE TABLE clause You have
previously specified, in your CREATE SYNCHRONIZATION
DEFINITION statement, the contents to be uploaded to the consolidated
database. Use these clauses to make changes to the specification.
Standards and ♦ Sybase Adaptive Server Anywhere version 7.0.
compatibility

196
Chapter 8 Reference

Example ♦ Alter the mytemplate synchronization template. Set different options. In


addition, the table Books is also uploaded to the consolidated database,
and only two columns of the People table is uploaded to the
consolidated database.
ALTER SYNCHRONIZATION TEMPLATE mytemplate
ADD OPTION verbose=’on’,
MODIFY OPTION memory=’3m’,
ADD TABLE Books,
MODIFY TABLE (People(fname,lname));

CREATE SYNCHRONIZATION DEFINITION statement


Function Use this statement to specify how to register with the MobiLink
synchronization server and to identify the contents that are to be uploaded
from the remote database to the consolidated database.
Syntax CREATE SYNCHRONIZATION DEFINITION SyncDefName
SITE SyncSiteName
[ TYPE SyncType ]
ADDRESS MLServerAddress
[ OPTION parameter=value, … ]
( TABLE article-description, … )
Parameters article-description:
table-name [ ( column-name, ... ) ]
[ WHERE search-condition ]
value:
’string’ | integer | "SQL variable name"
Permissions Must have DBA authority. Requires exclusive access to all tables named in
the article description.
Side effects Automatic commit
See also "ALTER SYNCHRONIZATION DEFINITION statement" on page 192
"DROP SYNCHRONIZATION DEFINITION statement" on page 206
"CREATE SYNCHRONIZATION TEMPLATE statement" on page 204
"CREATE SYNCHRONIZATION SITE statement" on page 202
Description Synchronization definitions are created in Adaptive Server Anywhere
database that are to serve as a MobiLink clients. Each definition specifies the
site name that uniquely identifies that logical MobiLink client within the
MobiLink setup. In addition, each site specifies how to contact the MobiLink
synchronization server and which data in the remote database is to be
synchronized with the consolidated database.

197
SQL statements

Using this statement, you can set options and choose a method of
synchronization. In addition, specify the contents that you wish to upload by
listing each table, followed by the column list and the WHERE clause. The
WHERE clause is a way of defining the subset of rows of a table to be
included in a synchronization.
Parameters SITE clause The name that uniquely identifies this remote site within your
MobiLink setup.

TYPE clause This clause specifies the method of synchronization. The


default value is tcpip. You may also choose to use http.

ADDRESS clause This clause specifies the location of the MobiLink


synchronization server.
Include the following parameter to encrypt all communication with the
MobiLink synchronization server.
♦ TCP/IP parameters These are chosen from the following list:
♦ host=hostname The host name or IP number for the machine on
which the MobiLink synchronization server is running. The default
value is localhost. For Windows CE, the default value is the value
of ipaddr in the registry folder Comm\Tcpip\Hosts\ppp_peer. This
allows a Windows CE device to connect to a MobiLink
synchronization server executing on the desktop machine where the
Windows CE device’s cradle is connected.
For the Palm Computing Platform, the default value of localhost
refers to the device. It is recommended that an explicit host name or
IP address be specified.
♦ port=portnumber The socket port number. The port number must
be a decimal number that matches the port the MobiLink
synchronization server is setup to monitor. The default value for the
port parameter is 2439, which is the IANA registered port number
for the MobiLink synchronization server.
♦ security=cipher{keyword=value;…} All communication through
this connection is to be encrypted using the cipher suite specified.
You can use only one cipher suite at a time. The only cipher suite
presently supported is certicom_tls, Certicom transmission-layer
security. The following security keywords are supported.
♦ certificate_company The UltraLite application only accepts
server certificates when the organization field on the certificate
matches this value. By default, this field is not checked.

198
Chapter 8 Reference

♦ certificate_unit The UltraLite application only accepts server


certificates when the organization unit field on the certificate
matches this value. By default, this field is not checked.
♦ certificate_name The UltraLite application only accepts
server certificates when the common name field on the
certificate matches this value. By default, this field is not
checked.
♦ trusted_certificates When synchronization occurs through a
Certicom TLS synchronization stream, the MobiLink
synchronization server sends its certificate to the client, as well
as the certificate of the entity that signed it, and so on up to a
self-signed root.
The client checks that the chain is valid and that it trusts the
root certificate in the chain. This feature allows you to specify
which root certificates to trust. By default, a Sybase certificate
and a Certicom certificate are the trusted roots.
♦ HTTP parameters These are chosen from the following list:
♦ host=hostname The host name or IP number for the machine on
which the MobiLink synchronization server is running. The default
value is localhost. For Windows CE, the default value is the value
of ipaddr in the registry folder Comm\Tcpip\Hosts\ppp_peer. This
allows a Windows CE device to connect to a MobiLink
synchronization server executing on the desktop machine where the
Windows CE device’s cradle is connected.
For the Palm Computing Platform, the default value of localhost
refers to the device. It is recommended that an explicit host name or
IP address be specified.
♦ port=portnumber The socket port number. The port number must
be a decimal number that matches the port the MobiLink
synchronization server is setup to monitor. The default value for the
port parameter is 2439, which is the IANA registered port number
for the MobiLink synchronization server.
♦ proxy_host=proxy_hostname The host name or IP address of
the proxy server. The default value is localhost.
♦ proxy_port=proxy_portnumber The port number of the proxy
server. The default value is 80.
♦ security=cipher{keyword=value;…} All communication through
this connection is to be encrypted using the cipher suite specified.
You can use only one cipher suite at a time. The only cipher suite
presently supported is certicom_tls, Certicom transmission-layer
security. The following security keywords are supported.
199
SQL statements

♦ certificate_company The UltraLite application only accepts


server certificates when the organization field on the certificate
matches this value. By default, this field is not checked.
♦ certificate_unit The UltraLite application only accepts server
certificates when the organization unit field on the certificate
matches this value. By default, this field is not checked.
♦ certificate_name The UltraLite application only accepts
server certificates when the common name field on the
certificate matches this value. By default, this field is not
checked.
♦ trusted_certificates When synchronization occurs through a
Certicom TLS synchronization stream, the MobiLink
synchronization server sends its certificate to the client, as well
as the certificate of the entity that signed it, and so on up to a
self-signed root.
The client checks that the chain is valid and that it trusts the
root certificate in the chain. This feature allows you to specify
which root certificates to trust. By default, a Sybase certificate
and a Certicom certificate are the trusted roots.
♦ url_suffix=suffix The suffix to add to the URL on the first line of
each HTTP request. When synchronizing through a proxy server,
the suffix may be necessary in order to find the MobiLink
synchronization server. The default value is MobiLink.
♦ version=versionnumber A string specifying the version of HTTP
to use. You have a choice of 1.0 or 1.1. The default value is 1.1.

OPTION clause The OPTION clause allows you to set the following. Set
the appropriate options using option=value in a comma-delimited list.
Below is the list of options available:

200
Chapter 8 Reference

Full Name Short Name Default value Descriptions


Stream sc MEDIUM Compress upload data
Compression stream: choose LOW,
MEDIUM, or HIGH.
Fire Triggers ft ON Fire triggers on download
Memory mem 1 Mb Memory used for
synchronization processing
Offline dir NULL Path containing offline
Directory transaction logs
Scripts Version sv default Specify the version of the
synchronization scripts that
the MobiLink
synchronization server is to
use when synchronizing
this client.
Send Triggers st OFF Send trigger actions on
upload
Verbose v OFF Verbose operation

The values for each option cannot contain the characters "=" or "," or ";".

Enter options carefully


The database engine will accept any option that you enter without
checking for its validity. Therefore, if you misspell an option, the engine
will not detect the error and no error message will be given until you run
the dbmlsync command to perform synchronization.

Standards and ♦ Sybase Adaptive Server Anywhere version 7.0.


compatibility
Example ♦ Use TCP/IP synchronization to upload the row(s) of the Pets table with
a pet_id of 2 as well as the person_id, fname, and lname columns of
the People table from the remote database to the consolidated database:
CREATE SYNCHRONIZATION DEFINITION mysharedtables
SITE ’demo_sync_site’
TYPE ’tcpip’
ADDRESS ’host=localhost;port=2439;’
OPTION memory=’2m’, dir=’c:\db\logs’
(table People( person_id, fname, lname ),
table Pets WHERE pet_id=2);

201
SQL statements

CREATE SYNCHRONIZATION SITE statement


Function Use this statement to create a site within a MobiLink reference database, to
be used when extracting remote Adaptive Server Anywhere client databases
with the mlxtract command-line utility.
Syntax CREATE SYNCHRONIZATION SITE SyncSiteName
USING SyncTemplateName
[TYPE SyncType]
[ADDRESS MLServerAddress]
[OPTION parameter=value]
Permissions Must have DBA authority.
Side effects Automatic commit
See also "ALTER SYNCHRONIZATION SITE statement" on page 194
"DROP SYNCHRONIZATION SITE statement" on page 206
"CREATE SYNCHRONIZATION DEFINITION statement" on page 197
"CREATE SYNCHRONIZATION TEMPLATE statement" on page 204
Description Synchronization templates and synchronization sites are used only when
creating remote Adaptive Server Anywhere databases by means of extracting
them from a MobiLink reference database.
Each remote database is created from a synchronization site, stored within
the reference database. Each synchronization site is based upon a single
synchronization template, although many sites can use a single template.
Information that is common to many sites should be stored in the
synchronization template, rather than be duplicated in each site.
The extraction process not only creates the remote databases, but also creates
a synchronization definition using properties of the corresponding
synchronization template and site. This information must include the unique
name of that MobiLink site within the MobiLink system. In addition, it
should specify how to contact the MobiLink synchronization server and
which data in the remote database is to be synchronized.
Using this statement to create a separate synchronization site for each remote
database. This statement also allows you to override the template settings.
For example, you can choose options different than those specified in the
template
Parameters SITE clause The name that uniquely identifies this remote site within your
MobiLink setup.

TYPE clause The TYPE clause specifies the method of synchronization.


The default value is tcpip. You may also choose to use http.

202
Chapter 8 Reference

ADDRESS clause The ADDRESS clause specifies the location of the


MobiLink synchronization server. The value of this clause overrides the
value in the synchronization template.
$ For a complete list of the available parameters, see "CREATE
SYNCHRONIZATION DEFINITION statement" on page 197.

OPTION clause The OPTION clause allows you to set the following
options. Set the appropriate options using a comma-delimited list.
The values for each option cannot contain the characters "=" or "," or ";".
Below is the list of options available:

Full Name Short Name Default value Descriptions


Stream sc MEDIUM Compress upload data
Compression stream: choose LOW,
MEDIUM, or HIGH.
Fire Triggers ft ON Fire triggers on download
Memory mem 1 Mb Memory used for
synchronization processing
Offline dir NULL Path containing offline
Directory transaction logs
Scripts Version sv default Specify the version of the
synchronization scripts that
the MobiLink
synchronization server is to
use when synchronizing
this client.
Send Triggers st OFF Send trigger actions on
upload
Verbose v OFF Verbose operation

Standards and ♦ Sybase Adaptive Server Anywhere version 7.0.


compatibility
Examples ♦ Deploy the template mytemplate to site demo_sync_site. Connect to a
different MobiLink synchronization server from the one specified in the
template and set the memory option to 3 Mb.
CREATE SYNCHRONIZATION SITE ’demo_sync_site’
USING mytemplate
ADDRESS ’host=test.internal;port=2439;’
OPTION memory=’3m’;
♦ Deploy the template mytemplate to site demo_sync_site using
Certicom transmission-layer security.

203
SQL statements

CREATE SYNCHRONIZATION SITE ’demo_sync_site’


USING mytemplate2
ADDRESS ’host=test.internal;port=2439;
security=certicom_tls’

CREATE SYNCHRONIZATION TEMPLATE statement


Function Use this statement to create a template within a MobiLink reference
database, to be used when extracting remote Adaptive Server Anywhere
client databases with the mlxtract command-line utility.
Syntax CREATE SYNCHRONIZATION TEMPLATE SyncTemplateName
[ TYPE SyncType ]
ADDRESS MLServerAddress
[ OPTION option=value]
( TABLE article-description, … )
Parameters article-description:
table-name [ ( column-name, ... ) ]
[ WHERE search-condition ]
value:
’string’ | integer | "SQL variable name"
Permissions Must have DBA authority. Requires exclusive access to all tables referred to
in the statement.
Side effects Automatic commit
See also "ALTER SYNCHRONIZATION TEMPLATE statement" on page 195
"DROP SYNCHRONIZATION TEMPLATE statement" on page 207
"CREATE SYNCHRONIZATION DEFINITION statement" on page 197
"CREATE SYNCHRONIZATION SITE statement" on page 202
Description Synchronization templates and synchronization sites are used only when
creating remote Adaptive Server Anywhere databases by means of extracting
them from a MobiLink reference database.
Each remote database is created from a synchronization site, stored within
the reference database. Each synchronization site is based upon a single
synchronization template, although many sites can use a single template.
Information that is common to many sites should be stored in the
synchronization template, rather than be duplicated in each site.

204
Chapter 8 Reference

The extraction process not only creates the remote databases, but also creates
a synchronization definition using properties of the corresponding
synchronization template and site. This information must include the unique
name of that MobiLink site within the MobiLink system. In addition, it
should specify how to contact the MobiLink synchronization server and
which data in the remote database is to be synchronized.
Use this statement to create a template for each type of remote database.
Parameters TYPE clause The TYPE clause specifies the method of synchronization.
The default value is tcpip. You may also choose to use http.

ADDRESS clause The ADDRESS clause specifies the location of the


MobiLink synchronization server.
$ For a complete list of the available parameters, see "CREATE
SYNCHRONIZATION DEFINITION statement" on page 197.

OPTION clause The OPTION clause allows you to set the following
options:
The values for each option cannot contain the characters "=" or "," or ";".
Below is the list of options available:

Full Name Short Name Default value Descriptions


Stream sc MEDIUM Compress upload data
Compression stream: choose LOW,
MEDIUM, or HIGH.
Fire Triggers ft ON Fire triggers on download
Memory mem 1 Mb Memory used for
synchronization processing
Offline dir NULL Path containing offline
Directory transaction logs
Scripts Version sv default Specify the version of the
synchronization scripts that
the MobiLink
synchronization server is to
use when synchronizing
sites that use this template.
Send Triggers st OFF Send trigger actions on
upload
Verbose v OFF Verbose operation

Standards and ♦ Sybase Adaptive Server Anywhere version 7.0.


compatibility

205
SQL statements

Example ♦ Use TCP/IP synchronization to upload the row(s) of the Pets table with
a pet_id of 2 as well as the person_id, fname, and lname columns of
the People table from the remote database to the consolidated database:
CREATE SYNCHRONIZATION TEMPLATE mytemplate
TYPE ’tcpip’
ADDRESS ’host=localhost;port=2439;’
OPTION memory=’2m’, dir=’c:\db\logs’
(table People( person_id, fname, lname ),
table Pets WHERE pet_id=2);

DROP SYNCHRONIZATION DEFINITION statement


Function Use this statement to drop a synchronization definition.
Syntax DROP SYNCHRONIZATION DEFINITION SyncDefName
Permissions Must have DBA authority.
Side effects Automatic commit.
See also "CREATE SYNCHRONIZATION DEFINITION statement" on page 197
"ALTER SYNCHRONIZATION DEFINITION statement" on page 192
Description Synchronization definitions are created in Adaptive Server Anywhere
database that are to serve as a MobiLink clients. Each definition specifies the
site name that uniquely identifies that logical MobiLink client within the
MobiLink setup. In addition, each site specifies how to contact the MobiLink
synchronization server and which data in the remote database is to be
synchronized with the consolidated database.
Use the DROP SYNCHRONIZATION DEFINITION statement to drop a
synchronization definition.
Note, however, that once a synchronization definition has been dropped,
outstanding updates (insert, delete, update and alter commands) will not be
synchronized.
Standards and ♦ Sybase Adaptive Server Anywhere version 7.0.
compatibility
Example ♦ Drop the mysharedtables synchronization definition.
DROP SYNCHRONIZATION DEFINITION mysharedtables;

DROP SYNCHRONIZATION SITE statement


Function Use this statement to drop a specific synchronization site.
Syntax DROP SYNCHRONIZATION SITE SyncSiteName
206
Chapter 8 Reference

Permissions Must have DBA authority.


Side effects Automatic commit.
See also "CREATE SYNCHRONIZATION SITE statement" on page 202
"ALTER SYNCHRONIZATION SITE statement" on page 194
Description Synchronization templates and synchronization sites are used only when
creating remote Adaptive Server Anywhere databases by means of extracting
them from a MobiLink reference database.
Each remote database is created from a synchronization site, stored within
the reference database. Each synchronization site is based upon a single
synchronization template, although many sites can use a single template.
Use the DROP SYNCHRONIZATION SITE statement to drop a specific
synchronization site.
Standards and ♦ Sybase Adaptive Server Anywhere version 7.0.
compatibility
Example ♦ The template mytemplate will no longer be deployed to the
new_sync_site remote site.
DROP SYNCHRONIZATION SITE new_sync_site;

DROP SYNCHRONIZATION TEMPLATE statement


Function Use this statement to drop a synchronization template.
Syntax DROP SYNCHRONIZATION TEMPLATE SyncTemplateName
Permissions Must have DBA authority.
Side effects Automatic commit. Dropping a synchronization template implicitly drops all
sites using that template.
See also "CREATE SYNCHRONIZATION TEMPLATE statement" on page 204
"ALTER SYNCHRONIZATION TEMPLATE statement" on page 195
Description Synchronization templates and synchronization sites are used only when
creating remote Adaptive Server Anywhere databases by means of extracting
them from a MobiLink reference database.
Each remote database is created from a synchronization site, stored within
the reference database. Each synchronization site is based upon a single
synchronization template, although many sites can use a single template.
Use the DROP SYNCHRONIZATION TEMPLATE statement to drop a
synchronization template.

207
SQL statements

Standards and ♦ Sybase Adaptive Server Anywhere version 7.0.


compatibility
Example ♦ Drop the mytemplate synchronization template.
DROP SYNCHRONIZATION TEMPLATE mytemplate;

START SYNCHRONIZATION DELETE statement


Function Use this statement to restart logging of deletes for MobiLink
synchronization.
Syntax START SYNCHRONIZATION DELETE
Permissions Must have DBA authority.
"STOP SYNCHRONIZATION DELETE statement" on page 208
See also
Description Ordinarily, Adaptive Server Anywhere automatically logs any changes made
to tables or columns that are part of a synchronization template and uploads
these changes to the consolidated database during the next synchronization.
You can temporarily suspend automatic logging of delete operations using
the STOP SYNCHRONIZATION DELETE statement. The START
SYNCHRONIZATION DELETE statement allows you to restart the
automatic logging.
When a STOP SYNCHRONIZATION DELETE statement is executed, none
of the delete operations executed on that connection will be synchronized.
The effect continues until a START SYNCHRONIZATION DELETE
statement is executed. The effects do not nest; that is, subsequent execution
of stop synchronization delete after the first will have no additional effect.
A single START SYNCHRONIZATION DELETE statement restarts the
logging, regardless of the number of STOP SYNCHRONIZATION
DELETE statements preceding it.
Standards and ♦ Sybase Adaptive Server Anywhere version 7.0.
compatibility

STOP SYNCHRONIZATION DELETE statement


Function Use this statement to temporarily stop logging of deletes for MobiLink
synchronization.
Syntax STOP SYNCHRONIZATION DELETE
Permissions Must have DBA authority.
"START SYNCHRONIZATION DELETE statement" on page 208
See also

208
Chapter 8 Reference

Description Ordinarily, Adaptive Server Anywhere automatically logs any changes made
to tables or columns that are part of a synchronization template and uploads
these changes to the consolidated database during the next synchronization.
This statement allows you to temporarily suspend logging of changes to a
remote Adaptive Server Anywhere database.
When a STOP SYNCHRONIZATION DELETE statement is executed, none
of the subsequent delete operations executed on that connection will be
synchronized. The effect continues until a START SYNCHRONIZATION
DELETE statement is executed. The effects do not nest; that is, subsequent
execution of stop synchronization delete after the first will have no additional
effect. A single START SYNCHRONIZATION DELETE statement restarts
the logging, regardless of the number of STOP SYNCHRONIZATION
DELETE statements preceding it.
This command can be useful to make corrections to a remote site, but should
be used with caution as it effectively disables MobiLink synchronization.
Standards and ♦ Sybase Adaptive Server Anywhere version 7.0.
compatibility

209
SQL statements

210
P A R T T H R E E

SQL Remote

This part describes the concepts, architecture, and features of SQL Remote.
The material in this part refers to both SQL Remote for Adaptive Server
Anywhere and SQL Remote for Adaptive Server Enterprise.

211
212
C H A P T E R 9

Welcome to SQL Remote

About this chapter This chapter introduces SQL Remote and the documentation.
Contents
Topic Page
About SQL Remote 214
About this manual 215
New features in version 7.0 217
New features in version 6.0.3 218
New features in version 6.0.2 220

213
About SQL Remote

About SQL Remote


SQL Remote is a data-replication technology designed for two-way
replication between a consolidated data server and large numbers of remote
databases, typically including many mobile databases.
SQL Remote replication is message based, and requires no direct server-to-
server connection. An occasional dial-up or e-mail link is sufficient.
Administration and resource requirements at the remote sites are minimal.
The time lag between the consolidated and remote databases is configurable,
and can range from minutes to hours or days.
Sybase SQL Remote technology is provided in two forms:
♦ SQL Remote for Adaptive Server Anywhere Enables replication
between a consolidated Adaptive Server Anywhere database and a large
number of remote databases.
♦ SQL Remote for Adaptive Server Enterprise Enables replication
between a consolidated Adaptive Server Enterprise database and a large
number of remote Adaptive Server Anywhere databases.
This book describes both of these technologies.
In a SQL Remote installation, you must have properly licensed SQL Remote
software at each participating database.
$ For a detailed introduction to SQL Remote concepts and features, see
"SQL Remote Concepts" on page 221.
$ For a list of supported operating systems and message links, see
"Supported Platforms and Message Links" on page 675.

214
Chapter 9 Welcome to SQL Remote

About this manual


This manual describes how to design, build, and maintain SQL Remote
installations.
The manual includes the following parts.
♦ Introduction to SQL Remote Replication concepts and features of
SQL Remote.
♦ Replication Design for SQL Remote Designing SQL Remote
installations.
♦ SQL Remote Administration Deploying SQL Remote databases and
administering a running SQL Remote setup.
♦ Reference SQL Remote commands, system tables, and other
reference material.

Platforms and products covered by this manual


This documentation applies to all supported platforms of SQL Remote. Not
all features are available on all platforms. The operating systems and features
you are entitled to use depends on the product you have purchased and your
license agreement.
Available formats The contents of this manual are provided online and in print. In some cases,
the print documentation must be purchased separately.

Online documentation most current


The online documentation contains the most current information about
SQL Remote. It is more authoritative than the printed manual.

Product installation
This section describes installation of SQL Remote for Adaptive Server
Enterprise. If you obtained SQL Remote as part of another product, consult
the installation instructions for the product you purchased.

v To install the SQL Remote software for PC’s:


1 Insert the CD-ROM into your CD-ROM drive.
2 If the installation program does not start automatically, start the setup
application on the CD-ROM.

215
About this manual

3 Follow the instructions in the installation program.

v To install the SQL Remote software for UNIX:


♦ Consult the instructions for your operating system in the Adaptive
Server Anywhere Read Me First booklet.
$ If you are using SQL Remote for Adaptive Server Enterprise, you must
install SQL Remote into any database you wish to replicate. For information
about installing SQL Remote into a database, see "Setting Up SQL Remote"
on page 233.

216
Chapter 9 Welcome to SQL Remote

New features in version 7.0


SQL Remote version 7.0 includes the following new features.
♦ Globally unique primary keys You can now use a DEFAULT
GLOBAL AUTOINCREMENT column in an Adaptive Server
Anywhere database, together with a GLOBAL_DATABASE_ID option
setting in each database, to guarantee unique primary keys throughout a
SQL Remote installation of Adaptive Server Anywhere databases. This
is a more convenient method than the more manual primary key pool
technique.
$ For more information, see "Using the default global autoincrement
feature" on page 357.
♦ Internal unload for dbxtract The dbxtract utility now uses the
UNLOAD statement introduced in Adaptive Server Anywhere
version 7.0 by default, rather than the slower OUTPUT statement.
Command-line options have been introduced to allow you to choose a
combination of internal (server-side) and external (client-side) unload
and load operations.
$ For a complete listing of command-line options, see "The
extraction command-line utility" on page 532.

Behavior changes
The following behavior has changed in version 7.0:
♦ dbxtract uses internal unload The default behavior of dbxtract is
now to use the UNLOAD statement to unload data on the server side,
rather than the OUTPUT statement to unload data on the client side. The
–ii, -ix, –xi, -xx command-line options allow you to choose which
combination of internal and external operations to use, and replace the
options –i and –x available in previous releases.
$ For a complete listing of command-line options, see "The
extraction command-line utility" on page 532.

217
New features in version 6.0.3

New features in version 6.0.3


In addition to bug fixes, SQL Remote version 6.0.3 includes the following
new features. Some features in Adaptive Server Anywhere that are
particularly relevant to SQL Remote are also included in this list:
♦ FTP and SMTP/POP support on UNIX The range of message systems
supported on UNIX operating systems has been expanded to include
FTP and SMTP/POP.
$ For a listing of supported operating and message systems, see
"Supported Platforms and Message Links" on page 675.
♦ Message link options stored in the database The message link
parameters that control SQL Remote behavior over each message
system can now be stored in the database as opposed to the registry. This
simplifies deployment and management issues related to message link
parameters.
$ For more information, see "Setting message type control
parameters" on page 445, "SET REMOTE OPTION statement" on
page 602, and "sp_link_option procedure" on page 626.
♦ Date and time replication formats You can now specify database
options that instruct SQL Remote what format to use when replicating
dates and times. These options are SR_time_format, SR_date_format,
and SR_timestamp_format.
$ For more information, see "Replication of dates and times" on
page 308, and "SQL Remote options" on page 542.
♦ Message Agent and SQL Remote Open Server run as a daemon
On UNIX operating systems you can run these applications as a daemon
using the -ud command-line option.
$ For more information, see "The Message Agent" on page 522, and
"The SQL Remote Open Server" on page 539.
♦ Easier unload and reload of Adaptive Server Anywhere databases
The dbunload utility has been enhanced (-ar command-line option) to
allow a single-step unload and reload of a database that can be used
whether or not your database is involved in replication.
$ For more information, see "Unload utility options" on page 128 of
the book ASA Reference, and "Designing rebuild and extract procedures"
on page 691 of the book ASA User’s Guide.
♦ Enhanced dblog output The dblog utility now displays additional
summary information, including offset information.

218
Chapter 9 Welcome to SQL Remote

$ For more information, see "The dblog command-line utility" on


page 120 of the book ASA Reference.
♦ dbtran utility enhancements The dbtran command-line utility
permits filtering of the transaction log operations to isolate subsets of
operations. This is of particular use to SQL Remote administrators.
$ For more information, see "The dbtran command-line utility" on
page 109 of the book ASA Reference.

Behavior changes
The following behavior has changed in version 6.0.3:
♦ Message link parameters stored in the database By default, the
message link parameters are now moved into the database when the
Message Agent is run for the first time with the new version of the
software. If you have software that explicitly accesses these parameters
in their old locations external to the database, it will be affected by this
change. You can continue using the old behavior by setting the
External_remote_options database option to ON.
♦ Passwords stored When a password is entered for a message link, it
was not stored in previous versions of the software. As the parameters
are now held in the database, a saved password is not held on disk and
so is more secure. Passwords are now saved by default. You can
continue using the old behavior by setting the Save_remote_passwords
option to OFF.

Upgrade issues
You can use the version 6.0.3 software with your existing databases.
You must upgrade Adaptive Server Anywhere databases to version 6.0.3 of
the software if you wish to take advantage of storing of message link
parameters in the database, or if you wish to use the datetime replication
options. You must upgrade the SQL Remote tables in your Adaptive Server
Enterprise database to be able to use these features.
$ For information on upgrading Adaptive Server Anywhere databases,
see "ALTER DATABASE statement" on page 371 of the book ASA
Reference, or "The Upgrade utility" on page 133 of the book ASA Reference.
$ For information on upgrading Adaptive Server Enterprise databases,
see "Upgrading SQL Remote for Adaptive Server Enterprise" on page 239.

219
New features in version 6.0.2

New features in version 6.0.2


In addition to bug fixes, SQL Remote version 6.0.2 includes the following
new features:
♦ Performance enhancements A major enhancement of the Adaptive
Server Anywhere Message Agent (dbremote) operational model for
scanning the transaction log and sending messages greatly improves the
range of achievable replication turnaround times.
Minimum lag times between entering data at one site and its replication
to another site were limited in earlier versions to times on the order of
ten minutes. With the new operational model, minimum lag times on the
order of seconds can be achieved in some circumstances.
When the Message Agent message-sending process runs in continuous
mode, it now stays (hovers) at the end of the active transaction log while
waiting for more data to be committed, instead of rescanning the
transaction log each time. This allows you to poll more frequently,
which can significantly reduce time for replication.
$ For more information, see "Tuning Message Agent performance"
on page 458.
♦ SQL Remote message logging New command-line options allow
you to tune message logging from these utilities.
$ For more information, see "The Message Agent" on page 522.

220
C H A P T E R 1 0

SQL Remote Concepts

About this chapter This chapter introduces the concepts, design goals, and features of
SQL Remote.
Contents
Topic Page
SQL Remote components 222
Publications and subscriptions 225
SQL Remote features 227
Some sample installations 229

221
SQL Remote components

SQL Remote components


The following components are required for SQL Remote:
♦ Data server An Adaptive Server Anywhere or Adaptive Server
Enterprise database-management system is required at each site to
maintain the data.
♦ Message Agent A SQL Remote Message Agent is required at the
consolidated site and at each remote site to send and receive
SQL Remote messages.
The Message Agent connects to the data server by a client/server
connection. It may run on the same machine as the data server or on a
different machine.
♦ Database extraction utility The extraction utility is used to prepare
remote databases from a consolidated database, during development and
testing, and also at deployment time.
♦ Message system client software SQL Remote uses existing message
systems to transport replication messages. A file-sharing "message
system" is provided, which does not require client software. Each
computer involved in SQL Remote replication using a message system
other than file sharing must have that message system installed.
♦ Client applications The applications that work with SQL Remote
databases are standard client/server database applications.

Message
Data server system
transport

Message Message
Agent system client

222
CHAPTER 10 SQL Remote Concepts

The data server


The data server may be an Adaptive Server Enterprise or an Adaptive Server
Anywhere server. At the remote site the data server is commonly an
Adaptive Server Anywhere personal server, but can also be an Adaptive
Server Enterprise or Adaptive Server Anywhere server.

Client applications
Client applications work with the data in the database. Client applications
use one of the client/server interfaces supported by the data server:
♦ For Adaptive Server Anywhere, the client application may use ODBC,
Embedded SQL, or Sybase Open Client to work with Adaptive Server
Anywhere.
♦ For Adaptive Server Enterprise, the client application may use one of the
Sybase Client Server interfaces, ODBC, or Embedded SQL.
Client applications do not have to know if they are using a consolidated or
remote database. From the client application perspective, there is no
difference.

The Message Agent


The SQL Remote Message Agent sends and receives replication messages.
It is a client application that sends and receives messages from database to
database. The Message Agent must be installed at both the consolidated and
at the remote sites.
For Adaptive Server Anywhere, the Message Agent is a program called
dbremote.exe on PC operating systems, and dbremote on UNIX.
For Adaptive Server Enterprise, the Message Agent is a program called
ssremote.exe on PC operating systems, and ssremote on UNIX.

223
SQL Remote components

Message
System

Message Agent Message Agent

Remote
Consolidated
database
database

Message system client


If you are using a shared file message system, no message system client is
needed.
If you are using an e-mail or other message system, you must have a message
system for that client in order to send and receive messages.

224
CHAPTER 10 SQL Remote Concepts

Publications and subscriptions


The data that is replicated by SQL Remote is arranged in publications. Each
database that shares information in a publication must have a subscription to
the publication.
Data is organized The publication is a database object describing data to be replicated. Remote
into publications users of the database who wish to receive a publication do so by subscribing
to a publication.
A publication may include data from several database tables. Each table’s
contribution to a publication is called an article. Each article may consist of
a whole table, or a subset of the rows and columns in a table.

A two-table publication

á á á á á
á á á á á
á á á á á + á á
á á á á á á á
á á á á á á á
Article 1: all of Article 2: some rows and
table A columns from table B

Periodically, the changes made to each publication in a database are


replicated to all subscribers to that publication. These replications are called
publication updates.
Messages are Remote databases subscribe to publications on the consolidated database so
always sent both that they can receive data from the consolidated database. To do this, a
ways subscription is created at the consolidated database, identifying the
subscriber by name and by the publication they are to receive.
SQL Remote always involves messages being sent two ways. The
consolidated database sends messages containing publication updates to
remote databases, and remote databases also send messages to the
consolidated database.

225
Publications and subscriptions

For example, if data in a publication at a consolidated database is updated,


those updates are sent to the remote databases. And even if the data is never
updated at the remote database, confirmation messages must still be sent
back to the consolidated database, to keep track of the status of the
replication.
Both databases Messages must be sent both ways, so not only does a remote database
subscribe subscribe to a publication created at the consolidated database, but the
consolidated database must subscribe to a corresponding publication created
at the remote database.

Data updates and


receipt confirmations

Publish Subscribe

Data updates and


receipt confirmations
Consolidated Subscribe Publish Remote
database database

When remote database users modify their own copies of the data, their
changes are replicated to the consolidated database. When the messages
containing the changes are applied at the consolidated database the changes
become part of the consolidated database’s publication, and are included in
the next round of updates to all remote sites (except the one it came from). In
this way, replication from remote site to remote site takes place via the
consolidated database.
Synchronizing a When a subscription is initially set up, the two databases must be brought to
remote database a state where they both have the same set of information, ready to start
replication. This process of setting up a remote database to be consistent with
the consolidated database is called synchronization. Synchronization can be
carried out manually, but the database extraction utility automates the
process. You can run the extraction utility from Sybase Central or as a
command-line utility.
The appropriate publication and subscription are created automatically at
remote databases when you use the SQL Remote database extraction utility
to create a remote database.

226
CHAPTER 10 SQL Remote Concepts

SQL Remote features


The following features are key to SQL Remote’s design.

Support for many subscribers SQL Remote is designed to support


replication with many subscribers to a publication.
This feature is of particular importance for mobile workforce applications,
which may require replication to the laptop computers of hundreds or
thousands of sales representatives from a single office database.

Transaction log-based replication SQL Remote replication is based on


the transaction log. This enables it to replicate only changes to data, rather
than all data, in each update. Also, log-base replication has performance
advantages over other replication systems.
The transaction log is the repository of all changes made to a database.
SQL Remote replicates changes made to databases as recorded in the
transaction log. Periodically, all committed transactions in the consolidated
database transaction log belonging to any publication are sent to remote
databases. At remote sites, all committed transactions in the transaction log
are periodically submitted to the consolidated database.
By replicating only committed transactions, SQL Remote ensures proper
transaction atomicity throughout the replication setup and maintains a
consistency among the databases involved in the replication, albeit with
some time lag while the data is replicated.

Central administration SQL Remote is designed to be centrally


administered, at the consolidated database. This is particularly important for
mobile workforce applications, where laptop users should not have to carry
out database administration tasks. It is also important in replication involving
small offices that have servers but little in the way of administration
resources.
Administration tasks include setting up and maintaining publications, remote
users, and subscriptions, as well as correcting errors and conflicts if they
occur.

Economical resource requirements The only software required to run


SQL Remote in addition to your Adaptive Server Anywhere or Adaptive
Server Enterprise DBMS is the Message Agent, and a message system. If
you use the shared file link, no message system software is required as long
as each remote user ID has access to the directory where the message files
are stored.

227
SQL Remote features

Memory and disk space requirements have been kept moderate for all
components of the replication system, so that you do not have to invest in
extra hardware to run SQL Remote.
Multi-platform support SQL Remote is provided on a number of
operating systems and message links.
$ For a list of supported environments, see "Supported Platforms and
Message Links" on page 675.

228
CHAPTER 10 SQL Remote Concepts

Some sample installations


While SQL Remote can provide replication services in many different
environments, its features are designed with the following characteristics in
mind:
♦ SQL Remote should be a solution even when no administration load can
be assigned to the remote databases, as in mobile workforce
applications.
♦ Data communication among the sites may be occasional and indirect: it
need not be permanent and direct.
♦ Memory and resource requirements at remote sites are assumed to be at
a premium.
The following examples show some typical SQL Remote setups.

Server-to-laptop replication for mobile workforces


SQL Remote provides two-way replication between a database on an office
network and personal databases on the laptop computers of sales
representatives. Such a setup may use an e-mail system as a message
transport.

229
Some sample installations

Consolidated
database

Office network
server

Remote
database Remote
database
Laptop computer
Laptop computer

Remote Remote
database database

Laptop computer Laptop computer

The office server may be running a server to manage the company database.
The Message Agent at the company database runs as a client application for
that server.
The laptop computers may be running Windows 95 or Windows NT, and
each sales representative has an Adaptive Server Anywhere personal server
to manage their own data.
While away from the office, a sales representative can make a single phone
call from their laptop to carry out the following functions:
♦ Collect new e-mail.
♦ Send any e-mail messages they have written.
♦ Collect publication updates from the office server.
♦ Submit any local updates, such as new orders, to the office server.
The updates may include, for example, new specials on the products the sales
representative handles, or new pricing and inventory information. These are
read by the Message Agent on the laptop and applied to the sales rep’s
database automatically, without requiring any additional action on the sales
representative’s part.

230
CHAPTER 10 SQL Remote Concepts

The new orders recorded by the sales representative are also automatically
submitted to the office without any extra action on the part of the sales
representative.

Server-to-server replication among offices


SQL Remote provides two-way replication between database servers at sales
offices or outlets and a central company office, without requiring database
administration experience at each sales office beyond the initial setup and
that required to maintain the server.
SQL Remote is not designed for up-to-the-minute data availability at each
site. Instead, it is appropriate where data can be replicated at periods of an
hour or so.
Such a setup may use an e-mail system to carry the replication, if there is
already a company-wide e-mail system. Alternatively, an occasional dial-up
system and file transfer software can be used to implement a FILE message
system.

Central office
database

Central office
network server
More...

Office Office
database database

Sales office server Sales office server

More...

Desktop computer Desktop computer

231
Some sample installations

SQL Remote is easy to configure to allow each office to receive their own
set of data. Tables that are of office interest only (staff records, perhaps, if
the office is a franchise) may be kept private in the same database as the
replicated data.
Layers can be added to SQL Remote hierarchies: for example, each sales
office server could act as a consolidated database, supporting remote
subscribers who work from that office.

232
C H A P T E R 1 1

Setting Up SQL Remote

About this chapter This chapter describes how to add SQL Remote capabilities to your Adaptive
Server Enterprise server.

Adaptive Server Enterprise users only


This chapter is required only for users of SQL Remote for Adaptive
Server Enterprise. SQL Remote capability is automatically installed into
Adaptive Server Anywhere databases.
This chapter assumes you have already installed the SQL Remote
software onto your machine.

Contents
Topic Page
Setup overview 234
Preparing your Adaptive Server Enterprise server 235
Upgrading SQL Remote for Adaptive Server Enterprise 239
Uninstalling SQL Remote 240

233
Setup overview

Setup overview
We call the collection of databases exchanging information using
SQL Remote an installation. From a physical point of view, a SQL Remote
installation may consist of hundreds or even thousands of databases sharing
information; but as SQL Remote keeps the information in each physical
database loosely consistent at a transactional level with that in other physical
databases, you can also think of the whole installation as a single dispersed
database.
Deploying a large-scale SQL Remote installation can involve setting up
databases on many machines. While some changes to the design and setup
configuration can be made on a running installation, it is highly
recommended that you deploy only when you have completed a careful
analysis and test of your design.
Setup tasks Setup of a SQL Remote installation includes the following tasks:
♦ Preparing your server for SQL Remote You must take some steps to
configure your Adaptive Server Enterprise to act as a SQL Remote site.
These include installing the SQL Remote system objects and the stable
queue system objects.
♦ Selecting message types You must decide whether you want to
exchange information by file sharing, e-mail, some other message type,
or a combination.
♦ Ensuring proper permissions are set Each user in the installation
requires permissions on both their own database and on the consolidated
database.
♦ Extracting remote databases You must extract an initial copy of
each remote database from the consolidated database.
This chapter describes each of these tasks.
All administration is Like all SQL Remote administrative tasks, setup is carried out by a database
at the consolidated administrator or system administrator at the consolidated database.
database
The Sybase System Administrator should perform all SQL Remote
configuration tasks. See your Adaptive Server Enterprise documentation for
more information about the Adaptive Server Enterprise environment.

234
Chapter 11 Setting Up SQL Remote

Preparing your Adaptive Server Enterprise


server
Before you start This section assumes the following:
♦ You have installed an Adaptive Server Enterprise server that is to
contain the SQL Remote database.
♦ You have installed the SQL Remote software on your computer. To
install the SQL Remote software, run the setup program from the CD-
ROM.
♦ You have created a database in the Adaptive Server Enterprise server
that will take part in your SQL Remote installation.
♦ You have system administrator permissions on the Adaptive Server
Enterprise server, and database owner permissions in the database.

Ensuring TEMPDB is large enough


SQL Remote uses the TEMPDB database for the following purposes:
♦ The database extraction utility used to create remote databases uses
TEMPDB to hold a temporary set of Adaptive Server Anywhere system
tables.
♦ The Message Agent creates a temporary table called #remote when it
connects to the server.
For these reasons, you should make TEMPDB larger than the 2 Mb default
size. The size required depends on the number of tables and columns in your
SQL Remote installation, but a size of 10 Mb is generally sufficient.

Installing SQL Remote into a database from Sybase Central


You can install SQL Remote into a database from the Sybase Central
graphical administration tool. Sybase Central is available on the
Windows NT and Windows 95 operating systems.

v To install SQL Remote into a database from Sybase Central:


1 Connect to Adaptive Server Enterprise from Sybase Central, as a user
with system administrator privileges.

235
Preparing your Adaptive Server Enterprise server

$ The login_id you use must correspond to the name used by the
Message Agent. For more information, see "The Message Agent and
replication security" on page 499.
2 Open the Databases folder for the server.
3 Open the SQL Remote folder in the database.
4 In the right pane, double-click Setup SQL Remote, and follow the
instructions in the Wizard.

Command-line installation of the SQL Remote system objects


For a database in your Adaptive Server Enterprise server to take part in a
SQL Remote installation, you must install a number of SQL Remote system
tables, views, and stored procedures in your database.

v To install the SQL Remote system objects:


1 Locate the SQL Remote initialization script ssremote.sql in your
SQL Remote installation directory.
2 Make a backup copy of the ssremote.sql script file. Then add the
following two lines to the beginning of ssremote.sql:
use database_name
go
where database_name is the name of the database to take part in
SQL Remote replication.
These two lines set the current database to database_name, so that the
SQL Remote tables are created in the database_name database. The
SQL Remote tables are owned by the database owner.
3 Run the script against your Adaptive Server Enterprise server.
Change to the directory containing the script file and enter the following
command line (which should be entered all on one line) to run the script:
isql -S server-name -U login_id -P password -i
ssremote.sql -o logfile
where server-name is the name of the Adaptive Server Enterprise,
login_id and password correspond to a user with system administrator
permissions on the server who owns the database, and logfile is the
name of a log file to hold the log information from the script.
$ The login_id must correspond to the name used by the Message
Agent. For more information, see "The Message Agent and replication
security" on page 499.

236
Chapter 11 Setting Up SQL Remote

4 Inspect the log file to confirm that the tables and procedures were
created without error.
The script creates a set of SQL Remote system objects in the database.

The SQL Remote system objects


The script creates the following objects in the database:
♦ SQL Remote system tables A set of tables used to maintain
SQL Remote information. These tables have names beginning with sr_.
♦ SQL Remote system views A set of views that hold the SQL Remote
information in a more understandable form. These views have names
beginning with sr_, and ending in s.
♦ SQL Remote system procedures A set of stored procedures used to
carry out SQL Remote configuration and administration tasks. These
procedures have names beginning with sp_, indicating their system
management roles.

Caution: Do not edit the SQL Remote system tables


Do not, under any circumstances, alter the SQL Remote system tables
directly. Doing so may corrupt the table and make it impossible for
SQL Remote to function properly. Use Sybase Central or the SQL Remote
system procedures to carry out all system administration tasks.

Command-line installation of the stable queue


The stable queue is a pair of database tables that hold transactions until they
are no longer needed by the replication system. Every Adaptive Server
Enterprise database participating in a SQL Remote installation needs a stable
queue.
$ For detailed information about the stable queue, see "The stable queue"
on page 495.
The stable queue can exist in the same database as the database taking part in
SQL Remote, or in a separate database. Keeping the stable queue in a
separate database complicates the backup and recovery plan, but can improve
performance by putting the stable queue workload on separate devices and/or
a separate Adaptive Server Enterprise server.

237
Preparing your Adaptive Server Enterprise server

v To install the stable queue:


1 Locate the stable queue initialization script stableq.sql in your
SQL Remote installation directory.
2 Make a backup copy of the stableq.sql script file. Then add the
following two lines to the beginning of stableq.sql:
use database_name
go
where database_name is the name of the database that will hold the
stable queue.
These two lines set the current database to database_name, so that the
stable queue is created in the database_name database. The stable queue
tables are owned by the database owner.
3 Run the script against your Adaptive Server Enterprise server.
Change to the directory holding the stable queue script, and enter the
following command line (which should be entered all on one line) to run
the script:
isql -S server-name -U login_id -P password -i
STABLEQ.SQL -o logfile
where server-name is the name of the Adaptive Server Enterprise,
login_id and password correspond to a user with system administrator
permissions on the server who owns the database, and logfile is the
name of a log file to hold the log information from the script.
$ The login_id must correspond to the name used by the Message
Agent. For more information, see "The Message Agent and replication
security" on page 499.
4 Inspect the log file to confirm that the tables and procedures were
created without error.

238
Chapter 11 Setting Up SQL Remote

Upgrading SQL Remote for Adaptive Server


Enterprise
This section describes the procedure for upgrading SQL Remote for
Adaptive Server Enterprise.
As a SQL Remote installation may consist of a large number of databases, it
is generally not practical to upgrade software on all machines at the same
time. SQL Remote is designed so that upgrades can be carried out
incrementally. It is not important what order SQL Remote machines are
upgraded, as the message format is compatible with previous releases.

v To upgrade SQL Remote:


1 Back up both the consolidated database and, if it is separate, the stable
queue database.
2 Install the new SQL Remote for Adaptive Server Enterprise software.
3 Run the script ssupdate.sql at the consolidated database to upgrade the
SQL Remote system tables and procedures.
The ssupdate.sql script is held in your Sybase directory.
4 Run the script squpdate.sql at the stable queue database to upgrade the
SQL Remote stable queue tables and procedures.
The squpdate.sql script is held in your Sybase directory.
The software is now upgraded.

239
Uninstalling SQL Remote

Uninstalling SQL Remote


This section describes how to uninstall the SQL Remote objects from a
database, and uninstall the stable queue from a database.

v To uninstall the SQL Remote objects from a database:


1 Connect to the database containing the SQL Remote objects, as a user
with dbo permissions.
2 Run the sp_drop_sql_remote stored procedure to remove all
SQL Remote objects apart from the procedure itself. The
sp_drop_sql_remote procedure is installed along with the other
SQL Remote objects.
exec sp_drop_sql_remote
go
3 Drop the sp_drop_sql_remote procedure to complete the uninsall
procedure.
drop procedure sp_drop_sql_remote
go

v To uninstall the stable queue from a database:


1 Connect to the database containing the stable queue, as a user with dbo
permissions.
2 Run the sp_queue_drop stored procedure to remove all stable queue
objects apart from the procedure itself. The sp_queue_drop procedure
is installed along with the other stable queue objects.
exec sp_queue_drop
go
3 Drop the sp_queue_drop procedure itself, to complete the uninstall
procedure.
drop procedure sp_queue_drop
go

240
C H A P T E R 1 2

A Tutorial for Adaptive Server Anywhere


Users

About this chapter This chapter guides you through setting up a simple replication system.
Contents
Topic Page
Tutorial overview 242
A tutorial using Sybase Central 245
Setting up a consolidated database 248
Set up the remote database in Sybase Central 253
A tutorial using Interactive SQL and DBXTRACT 255
Set up the consolidated database 257
Set up the remote database 261
Start replicating data 263
A sample publication 267

241
Tutorial overview

Tutorial overview
This tutorial describes how to set up a simple SQL Remote replication
system using Adaptive Server Anywhere.

Tutorial goals
In the tutorial you act as the system administrator of a consolidated Adaptive
Server Anywhere database, and set up a simple replication system. The
replication system consists of a simple sales database, with two tables.
The consolidated database holds all of the database, while the remote
database has all of one table, but only some of the rows in the other table.
The tutorial takes you through the following steps:
♦ Creating a consolidated database on your Adaptive Server Anywhere
server.
♦ Creating a file-sharing replication system with a single Adaptive Server
Anywhere remote database.
♦ Replicating data between the two databases.

The database
The tutorial uses a simple two-table database. One table holds information
about sales representatives, and the other about customers. The tables are
much simpler than you would use in a real database; this allows us to focus
just on those issues important for replication.
Database schema The database schema for the tutorial is illustrated in the figure.

Customer SalesRep
cust_key char(10) rep_key = rep_key char(5)
name char(40) rep_key name char(40)
rep_key char(5)

Features to note include the following:


♦ Each sales representative is represented by one row in the SalesRep
table.
♦ Each customer is represented by one row in the Customer table.

242
CHAPTER 12 A Tutorial for Adaptive Server Anywhere Users

♦ Each customer is assigned to a single sales representative, and this


assignment is built in to the database as a foreign key from the Customer
table to the SalesRep table. The relationship between the Customer table
and the SalesRep table is many-to-one.

The tables in the The tables are described in more detail as follows:
database
Table Description
SalesRep One row for each sales representative that works for the
company. The SalesRep table has the following columns:
♦ rep_key An identifier for each sales representative. This is
the primary key.
♦ name The name of each sales representative.
The SQL statement creating this table is as follows:
CREATE TABLE SalesRep (
rep_key CHAR(12) NOT NULL,
name CHAR(40) NOT NULL,
PRIMARY KEY (rep_key)
)
Customer One row for each customer that does business with the
company. The Customer table includes the following columns:
♦ cust_key An identifier for each customer. This is the
primary key.
♦ name The name of each customer.
♦ rep_key An identifier for the sales representative in a sales
relationship. This is a foreign key to the SalesRep table.

The SQL statement creating this table is as follows:


CREATE TABLE Customer (
cust_key CHAR(12) NOT NULL,
name CHAR(40) NOT NULL,
rep_key CHAR(12) NOT NULL,
FOREIGN KEY ( rep_key )
REFERENCES SalesRep (rep_key ),
PRIMARY KEY (cust_key)
)

Replication goals
The goals of the replication design are to provide each sales representative
with the following information:
♦ The complete SalesRep table.
♦ Those customers assigned to them.
243
Tutorial overview

The tutorial describes how to meet this goal using SQL Remote.

Sybase Central or command-line utilities


Use Sybase The tutorial material is presented twice. One section describes how to set up
Central or the the installation using the Sybase Central management utility. The second
command line section describes how to set up the installation using command-line utilities:
this requires typing commands individually.
Where next? ♦ To work through the tutorial using Sybase Central, go to "A tutorial
using Sybase Central" on page 245, next.
♦ To work through the tutorial entering commands explicitly, go to "A
tutorial using Interactive SQL and DBXTRACT" on page 255.

244
CHAPTER 12 A Tutorial for Adaptive Server Anywhere Users

A tutorial using Sybase Central


The following sections are a tutorial describing how to set up a simple
SQL Remote replication system in Adaptive Server Anywhere using Sybase
Central.
You do not need to enter SQL statements if you are using Sybase Central to
administer SQL Remote. A tutorial for those who do not have access to
Sybase Central, or who prefer to work with command-line utilities, is
presented in "A tutorial using Interactive SQL and DBXTRACT" on
page 255. This tutorial contains the SQL statements executed behind the
scenes by Sybase Central.
In this tutorial you act as the DBA of the consolidated database, and set up a
simple replication system using the file-sharing message link. The simple
example is a primitive model for a sales-force automation system, with two
tables. One contains a list of sales representatives, and another a list of
customers. The tables are replicated in a setup with one consolidated
database and one remote database. You can install this example on one
computer.
$ This tutorial assumes that you have some familiarity with Sybase
Central. For an introduction to Sybase Central, see "Managing Databases
with Sybase Central" on page 35 of the book Introducing SQL Anywhere
Studio.

Preparing for the Sybase Central replication tutorial


This section describes the steps you need to take to prepare for the tutorial.
These steps include the following:
♦ Create the directories and databases required for the tutorial.
♦ Add the tables to the consolidated database.

v To prepare for the tutorial:


1 Create a directory to hold the files you make during this tutorial; for
example c:\tutorial.
mkdir c:\tutorial
2 Create a subdirectory for each of the two user IDs in the replication
system, to hold their messages. Create these subdirectories using the
following statements at a system command line:
mkdir c:\tutorial\hq
mkdir c:\tutorial\field

245
A tutorial using Sybase Central

3 The tutorial uses two databases: a consolidated database named hq.db


and a remote database named field.db. At this point, you should create
the hq database with the Create Database utility in Sybase Central:
♦ Start Sybase Central. You will be creating a new database so you do
not have to connect to any particular existing database.
♦ Open the Utilities folder in the left panel.
♦ Double-click Create Database in the right panel. The Create
Database wizard is displayed.
♦ Create a database with filename c:\tutorial\hq.db.
♦ You can use the default settings for this database. Make sure you
elect to maintain a transaction log. Replication cannot take place
without a transaction log.
An Adaptive Server Anywhere database is simply a file, which can be
copied to other locations and computers when necessary.
The next step is to add a pair of tables to the consolidated database.

v To add tables to the consolidated database:


1 Connect to the hq database from Sybase Central, with a user ID of DBA
and a password of SQL.
2 Click the Tables folder of the hq database.
3 Double-click Add Table, and use the Table Editor to create a table
named SalesRep with the following columns:

Key Column Data Type Size/Prec


Primary key Rep_key Char 5
Name Char 40

You do not need to use the Column Properties or the Advanced Table
Properties dialogs. The columns are created by default not allowing
NULL.
4 Save the table and close the Table Editor.
5 Double-click Add Table again, and use the Table Editor to create a table
named Customer with the following columns:

246
CHAPTER 12 A Tutorial for Adaptive Server Anywhere Users

Key Column Data Type Size/Prec


Primary key Cust_key Char 10
Name Char 40
Rep_key Char 5

Again, you do not need to use the property sheets. The columns are
created by default not allowing NULL.
6 Save the table and close the Table Editor.
7 In the Tables folder, open the Customer table container and then open
the Foreign Keys folder within this table.
8 Double-click Add Foreign Key. Using the wizard, add a foreign key to
the rep_key column of the SalesRep table. You can use the default
settings for this foreign key.
You are now ready for the rest of the tutorial.

247
Setting up a consolidated database

Setting up a consolidated database


This section of the tutorial describes how to prepare the consolidated
database of a simple replication system.
Preparing a consolidated database for replication involves the following
steps:
1 Create a message type to use for replication.
2 Grant PUBLISH permissions to a user ID to identify the source of
outgoing messages.
3 Grant REMOTE permissions to all user IDs that are to receive messages.
4 Create a publication describing the data to be replicated.
5 Create subscriptions describing who is to receive the publication.
You require DBA authority to carry out these tasks.

Add a SQL Remote message type


All messages sent as part of replication use a message type. A message type
description has two parts:
♦ A message link supported by SQL Remote. In this tutorial, we use the
FILE link.
♦ An address for this message link, to identify the source of outgoing
messages.
Adaptive Server Anywhere databases already have message types created,
but you need to supply an address for the message type you will use.

v To add an address to a message type:


1 From Sybase Central, connect to the HQ database.
2 Open the SQL Remote folder for the HQ database.
3 Within the SQL Remote folder, open the Message Types folder.
4 In the right pane, right-click the FILE message type and choose
Properties from the popup menu.
5 Enter a publisher address to provide a return address for remote users.
Enter the directory you have created to hold messages for the
consolidated database (hq).

248
CHAPTER 12 A Tutorial for Adaptive Server Anywhere Users

The address is taken relative to the SQLRemote environment variable or


registry entry. As you have not set this value, the address is taken
relative to the directory from which the Message Agent is run. You
should run the Message Agent from your tutorial directory for the
addresses to be interpreted properly.
$ For information about setting the SQLRemote value, see "Setting
message type control parameters" on page 445.
6 Click OK to save the message type.

Add the publisher and remote user to the database


In SQL Remote’s hierarchical replication system, each database may have
zero or one database immediately above it (the consolidated database) and
zero or more databases immediately below it (remote databases).
In this tutorial, the current database is the consolidated database of a two-
level system. It has no database above it, and only one remote database
below it.
The following diagram illustrates the two databases:

Database: hq
Publisher: hq_user
hq Remote user: field_user

Database: field
Publisher: field_user
field
Consolidated user:
hq_user

For any database in a SQL Remote replication setup, there are three
permissions that may be granted to identify databases on the hierarchy:
♦ PUBLISH permission Identifies the current database in all outgoing
messages
♦ REMOTE permission Identifies each database receiving messages
from the current database that is below it on the hierarchy
♦ CONSOLIDATE permission Identifies a database receiving messages
from the current database that is directly above it on the hierarchy.

249
Setting up a consolidated database

Permissions can only be granted by a user with DBA authority. To carry out
these examples you should connect from Sybase Central to the hq database
as user ID DBA, with password SQL.
Add a database Any database, consolidated or remote, that distributes changes to other
publisher user ID databases in the replication system is a publisher database. Each database in
the replication system is identified by a single user ID. You set that ID for
your database by adding a publisher to the database. This section describes
setting permissions for the consolidated hq database.
First create a user ID named hq_user, who will be the publisher user ID.

v To create a new user as the publisher:


1 Open the Users & Groups folder.
2 Double-click Add User. The New User wizard is displayed.
3 Enter the name hq_user, with password hq_pwd, and click Next.
4 On the next page, ensure that the user is granted Remote DBA authority,
making it possible for this user to run the Message Agent. Then click
Next.
5 On the final page, check the box identifying this user ID as the
publisher. Then click Finish to create the user.
A database can have only one publisher. You can find out who the publisher
is at any time by opening the SQL Remote folder.
You can also make an existing user the publisher by right-clicking the user in
the Users & Groups folder and choosing Set as Publisher from the popup
menu.
Add a remote user Each remote database is identified in the consolidated database by a user ID
with REMOTE permissions. Whether the remote database is a personal
database server or a network server with many users, it needs a single user
ID to represent it to the consolidated database.
In a mobile workgroup setting, remote users may already be users of the
consolidated database, and so no new users would need to be added;
although they would need to be set as remote users.
When a remote user is added to a database, the message system they use and
their address under that message system need to be stored along with their
database user ID.

v To add a remote user:


1 Open the Remote Users folder (located within the SQL Remote folder).
2 Double-click Add Remote User.

250
CHAPTER 12 A Tutorial for Adaptive Server Anywhere Users

3 In the wizard, create a remote user with user ID field_user, password


field_pwd, message type file, and address field. For the message type
and address, select the FILE type and the corresponding address you are
using for this user (such as field).
As with the publisher address, the address of the remote user is taken
relative to the SQLRemote environment variable or registry entry. As
you have not set this value, the address is taken relative to the directory
from which the Message Agent is run. You should run the Message
Agent from your tutorial directory for the addresses to be interpreted
properly.
$ For information about setting the SQLRemote value, see "Setting
message type control parameters" on page 445.
4 On the next page, ensure that the Send Then Close option is checked. (In
many production environments you would not choose Send Then Close,
but it is convenient for this tutorial.)
5 On the next page ensure that the Remote DBA authority is checked, so
that the user can run the Message Agent.
6 When you have finished all the entries, click Finish to create the remote
user.
You have now created the users who will use this system.

Add publications and subscriptions


This section describes how to add a publication to a database, and how to add
a subscription to that publication for a user. The publication replicates all
rows of the table SalesRep and some of the rows of the Customer table.

v To add a publication:
1 Click the Publications folder in the SQL Remote folder.
2 Double-click Add Publication. The Publication wizard is displayed.
3 Name the publication SalesRepData on the first page of the wizard.
4 On the next page, click Add Table
5 In the resulting dialog, select SalesRep from the list. Leave the All
columns option selected, and click OK to exit the dialog and return to
the wizard.
6 Click Add Table again, and select Customer from the list in the dialog.
Again, leave the All columns option selected.

251
Setting up a consolidated database

7 Leave the dialog open and click the Subscribe Restriction tab. On this
tab, choose to subscribe by the column rep_key. Click OK to add the
table to the publication.
8 Follow the rest of the instructions in the wizard.

Add a subscription Each user ID that is to receive changes to a publication must have a
subscription to that publication. Subscriptions can only be created for a
valid remote user. You need to add a subscription to the SalesRepData
publication for the remote database user field_user.

v To add a subscription:
1 Open the Publications folder (located within the SQL Remote folder).
2 Right-click the SalesRepData publication and choose Properties from
the popup menu.
3 Click the Subscriptions tab.
4 Click Subscribe For and choose to subscribe field_user.
You have now set up the consolidated database.

252
CHAPTER 12 A Tutorial for Adaptive Server Anywhere Users

Set up the remote database in Sybase Central


The remote database needs to be created and configured in order to send and
receive messages and participate in a SQL Remote setup.
Like the consolidated database, the remote database needs a publisher (in this
case, the field_user user ID) to identify the source of outgoing messages,
and it needs to have hq_user identified as a user with consolidated
permissions. It needs the SalesRepData publication to be created and needs
a subscription created for the hq_user user ID.
The remote database also needs to be synchronized with the consolidated
database; that is, it needs to have a current copy of the data in order for the
replication to start. In this case, there is no data in the publication as yet.
The database extraction utility enables you to carry out all the steps needed
to create a remote database complete with subscriptions and required user
IDs.
You need to extract a database from the consolidated database for remote
user field_user.

v To extract a database:
1 Connect to the hq database.
2 Right-click the database and choose Extract Database from the popup
menu.
3 Click Next on the first page of the wizard.
4 Choose to Start Subscriptions Automatically, for user field_user.
5 Create the database as file c:\tutorial\field.db, using a transaction log of
name field.log in the same directory.
6 Choose to extract all parts of the schema.
7 Leave the other options at their default settings, and create the remote
database.
In a proper SQL Remote setup, the remote database field would need to be
loaded on to the computer using it, together with an Adaptive Server
Anywhere server and any client applications required. For this tutorial, we
leave the database where it is and use Interactive SQL to input and replicate
data.
You should connect to the field database as DBA and confirm that all the
database objects are created. These include the SalesRep and Customer
tables, the SalesRepData publication, and the subscription for the
consolidated database.

253
Set up the remote database in Sybase Central

What next? The system is now ready for replication.


$ For the next step, inserting and replicating data, see the section "Start
replicating data" on page 263.

254
CHAPTER 12 A Tutorial for Adaptive Server Anywhere Users

A tutorial using Interactive SQL and DBXTRACT


The following sections are a tutorial describing how to set up a simple
SQL Remote replication system for users without Windows 95 or
Windows NT 3.51 or later, who cannot run Sybase Central. It may also be
useful to users of Sybase Central who prefer to use command-line tools or
who want to know what Sybase Central is doing behind the scenes.
This tutorial describes the SQL statements for managing SQL Remote, which
can be run from Interactive SQL. It also describes how to run the dbxtract
command-line utility to extract remote databases from a consolidated
database.
In this tutorial you act as the DBA of the consolidated database, and set up a
simple replication system using the file-sharing message link. The simple
example is a primitive model for a sales-force automation system, with two
tables. One contains a list of sales representatives, and another a list of
customers. The tables are replicated in a setup with one consolidated
database and one remote database. You can install this example on one
computer.

Preparing for the replication tutorial


This section describes the steps you need to take to prepare for the tutorial.
These steps include the following:
♦ Create the directories and databases required for the tutorial.
♦ Add a table to the consolidated database.

v To create the databases and directories for the tutorial:


1 Create a directory to hold the files you make during this tutorial; for
example c:\tutorial.
mkdir c:\tutorial
2 The tutorial uses two databases: a consolidated database named hq.db
and a remote database named field.db. Change to the tutorial directory
and create these databases using the following statements at a command
line:
dbinit hq.db
dbinit field.db

255
A tutorial using Interactive SQL and DBXTRACT

The database initialization tool for Windows 3.x is dbinitw rather than
dbinit. Under Windows 3.x, you should execute the commands from the
Program Manager File➤Run menu or you could make an icon for each
command.
3 Create a subdirectory for each of the two user IDs in the replication
system. Create these subdirectories using the following statements at a
command line:
mkdir c:\tutorial\hq
mkdir c:\tutorial\field

The next step is to add a pair of tables to the consolidated database.

v To add the tables to the consolidated database:


1 Connect to hq.db from Interactive SQL with a user ID of DBA and a
password of SQL.
2 Execute the following CREATE TABLE statement to create the
SalesRep table:
CREATE TABLE SalesRep (
rep_key CHAR(12) NOT NULL,
name CHAR(40) NOT NULL,
PRIMARY KEY ( rep_key )
);
3 Execute the following CREATE TABLE statement to create the
Customer table:
CREATE TABLE Customer (
cust_key CHAR(12) NOT NULL,
name CHAR(40) NOT NULL,
rep_key CHAR(12) NOT NULL,
FOREIGN KEY REFERENCES SalesRep,
PRIMARY KEY ( cust_key )
);

You are now ready for the rest of the tutorial.

256
CHAPTER 12 A Tutorial for Adaptive Server Anywhere Users

Set up the consolidated database


This section of the tutorial describes how to set up the consolidated database
of a simple replication system.
You require DBA authority to carry out this task.

Create a SQL Remote message type


All messages sent as part of replication use a message type. A message type
description has two parts:
♦ A message link supported by SQL Remote. In this tutorial, we use the
FILE link.
♦ An address for this message link, to identify the source of outgoing
messages.

v To create the message type:


♦ In Interactive SQL, create the file message type using the following
statement:
CREATE REMOTE MESSAGE
TYPE file
ADDRESS ’hq’
The address (hq) for a file link is a directory in which files containing
the message are placed. It is taken relative to the SQLRemote
environment variable or registry entry. As you have not set this value,
the address is taken relative to the directory from which the Message
Agent is run. You should run the Message Agent from your tutorial
directory for the addresses to be interpreted properly.
$ For information about setting the SQLRemote value, see "Setting
message type control parameters" on page 445.

Grant PUBLISH and REMOTE at the consolidated database


In the hierarchical replication system supported by SQL Remote, each
database may have one consolidated database immediately above it in the
hierarchy and many databases immediately below it on the hierarchy (remote
databases).

257
Set up the consolidated database

PUBLISH permission identifies the current database for outgoing messages,


and the REMOTE permission identifies each database receiving messages
from the current database.
Permissions can only be granted by a user with DBA authority. To carry out
these examples you should connect using the Interactive SQL utility to hq as
user ID DBA, with password SQL.
GRANT PUBLISH Each database that distributes its changes to other databases in the replication
to identify outgoing system is a publisher database. Each database in the replication system that
messages publishes changes to a database is identified by a single user ID. You set that
ID for your database using the GRANT PUBLISH statement. This section
describes setting permissions for the consolidated database (hq.db).

v To create a publisher for the database:


♦ Connect to the database using Interactive SQL, and type the following
statement:
GRANT CONNECT
TO hq_user
IDENTIFIED BY hq_pwd ;

GRANT PUBLISH TO hq_user ;

You can check the publishing user ID of a database at any time using the
CURRENT PUBLISHER special constant:
SELECT CURRENT PUBLISHER

GRANT REMOTE Each remote database is identified using the GRANT REMOTE statement.
for each database Whether the remote database is a personal server or a network server with
to which you send many users, it needs a single user ID to represent it to the consolidated
messages database.
In a mobile workgroup setting, remote users may already be users of the
consolidated database, and so this would require no extra action on the part
of the DBA.
The GRANT REMOTE statement identifies the message system to be used
when sending messages to the recipient, as well as the address.

v To add a remote user:


♦ Connect to the database using Interactive SQL, and execute the
following statements:
GRANT CONNECT TO field_user
IDENTIFIED BY field_pwd ;

GRANT REMOTE TO field_user


TYPE file ADDRESS ’field’ ;

258
CHAPTER 12 A Tutorial for Adaptive Server Anywhere Users

The address string is the directory used to hold messages for field_user,
enclosed in single quotes. It is taken relative to the SQLRemote
environment variable or registry entry. As you have not set this value,
the address is taken relative to the directory from which the Message
Agent is run. You should run the Message Agent from your tutorial
directory for the addresses to be interpreted properly.
$ For information about setting the SQLRemote value, see "Setting
message type control parameters" on page 445.

Create publications and subscriptions


A publication is created using a CREATE PUBLICATION statement. This is
a data definition language statement, and requires DBA authority. For the
tutorial, you should connect to the hq database as user ID DBA, password
SQL, to create a publication.

Set up a Create a publication named SalesRepData, which replicates all rows of the
publication at the table SalesRep, and some of the rows of the table Customer.
consolidated
database v To create the publication:
♦ Connect to the database from Interactive SQL, and execute the
following statement:
CREATE PUBLICATION SalesRepData (
TABLE SalesRep,
TABLE Customer SUBSCRIBE BY rep_key
)

Set up a Each user ID that is to receive changes to the publication must have a
subscription subscription. The subscription can only be created for a user who has
REMOTE permissions. The GRANT REMOTE statement contains the
address to use when sending the messages.

v To create the subscription:


♦ Connect to the database from Interactive SQL, and execute the
following statement:
CREATE SUBSCRIPTION
TO SalesRepData (’rep1’)
FOR field_user ;
The value rep1 is the rep_key value we will give to the user field_user
in the SalesRep table.

259
Set up the consolidated database

The full CREATE SUBSCRIPTION statement allows control over the data
in subscriptions; allowing users to receive only some of the rows in the
publication. For more information, see "CREATE SUBSCRIPTION
statement" on page 583.
The CREATE SUBSCRIPTION statement identifies the subscriber and
defines what they receive. However, it does not synchronize data, or start the
sending of messages.

260
CHAPTER 12 A Tutorial for Adaptive Server Anywhere Users

Set up the remote database


The remote database needs to be configured in order to send and receive
messages and participate in a SQL Remote setup. Like the consolidated
database, the remote database needs a CURRENT PUBLISHER to identify
the source of outgoing messages, and it needs to have the consolidated
database identified as a subscriber. The remote database also needs the
publication to be created and needs a subscription created for the
consolidated database. The remote database also needs to be synchronized
with the consolidated database; that is, it needs to have a current copy of the
data in order for the replication to start.
The dbxtract utility enables you to carry out all the steps needed to create a
remote database complete with subscriptions and required user IDs.

Extract the remote database information


Leave the hq database running, and change to the tutorial directory.
Type the following command at the system command line (all on one line) to
extract a database for the user field_user from the consolidated database:
dbxtract -v -c "dbn=hq;uid=dba;pwd=sql" c:\tutorial
field_user

The -v command-line switch produces more verbose output. This is useful


during development.
This command assumes the hq database is currently running on the default
server. If the database is not running, you should enter a database file
parameter in the connection string:
dbf=hq.db
instead of the dbn database name parameter.
$ For details of the dbxtract utility and its options, see "The extraction
command-line utility" on page 532.
The dbxtract command creates a SQL command file named reload.sql in the
current directory and a data file in the c:\tutorial directory. It also starts the
subscriptions to the remote user.
The next step is to load these files into the remote database.

261
Set up the remote database

Load the remote database information

v To load the database information:


1 From the tutorial directory, connect to the remote database field.db from
Interactive SQL with a user ID of DBA and a password of SQL.
2 Run the reload.sql command file:
READ C:\tutorial\reload.sql

The reload.sql command file carries out the following tasks:


♦ Creates a message type at the remote database.
♦ Grants PUBLISH and REMOTE permissions to the remote and
consolidated database, respectively.
♦ Creates the table in the database. If the table had contained any data
before extraction, the command file would fill the replicated table with a
copy of the data.
♦ Creates a publication to identify the data being replicated.
♦ Creates the subscription for the consolidated database, and starts the
subscription.
While connected to the field database as DBA, confirm that the tables are
created by executing the following statements:
SELECT * FROM SalesRep ;

SELECT * FROM Customer ;

What next? The system is now ready for replication.


$ For the next step, inserting and replicating data, see the section "Start
replicating data" on page 263 .

262
CHAPTER 12 A Tutorial for Adaptive Server Anywhere Users

Start replicating data


You now have a replication system in place. In this section, data is replicated
from the consolidated database to the remote database, and from the remote
to the consolidated database.

Enter data at the consolidated database


First, enter some data into the consolidated database.

v To enter data at the consolidated database:


1 Connect to the consolidated database hq from the Interactive SQL utility
with a user ID of DBA and a password of SQL.
2 Insert two rows into the SalesRep table and commit the insertion by
executing the following statement:
INSERT INTO SalesRep (rep_key, name)
VALUES (’rep1’, ’Field User’) ;
INSERT INTO SalesRep (rep_key, name)
VALUES (’rep2’, ’Another User’) ;
COMMIT ;
3 Insert two rows into the Customer table and commit the insertion by
executing the following statement:
INSERT INTO Customer (cust_key, name, rep_key)
VALUES (’cust1’, ’Ocean Sports’, ’rep1’ ) ;
INSERT INTO Customer (cust_key, name, rep_key)
VALUES (’cust2’, ’Sports Plus’, ’rep2’ ) ;
COMMIT ;
4 Confirm that the data has been entered by executing the following
statements:
SELECT *
FROM SalesRep;

SELECT *
FROM Customer;

The next step is to send the relevant rows to the remote database.

263
Start replicating data

Send data from the consolidated database


To send the rows to the remote database, you must run the Message Agent at
the consolidated database. The dbremote program is the Message Agent for
Adaptive Server Anywhere.

v To send the data to the remote database:


1 From a command prompt, change to your tutorial directory. For
example,
> c:
> cd c:\tutorial
2 Enter the following statement at the command line to run the Message
Agent against the consolidated database:
dbremote -c "dbn=hq;uid=dba;pwd=sql"
This command line assumes that the hq database is currently running on
the default server. If the database is not running, you must supply a dbf
parameter with the database file name instead of the dbn parameter.
$ For more information on dbremote command line switches, see
"The Message Agent" on page 522.
3 Click Shutdown on the Message Agent window to stop the Message
Agent when the messages have been sent. The Message Agent window
displays the message Execution completed when all processing is
complete.

Receive data at the remote database


To receive the insert statement at the remote database, you must run the
Message Agent, dbremote, at the remote database.

v To receive data at the remote database:


1 From a command prompt, change to your tutorial directory. For
example,
> c:
> cd c:\tutorial
2 Enter the following statement at the command line to run the Message
Agent against the field database:
dbremote -c "dbn=field;uid=dba;pwd=sql"
This command line assumes that the field database is currently running
on the default server.
264
CHAPTER 12 A Tutorial for Adaptive Server Anywhere Users

$ For more information on dbremote command line switches, see


"The Message Agent" on page 522.
3 Click Shutdown on the Message Agent window to stop the Message
Agent when the messages have been processed. The Message Agent
window displays the message Execution completed when all processing
is complete.
The Message Agent window displays status information while running. This
information can be output to a log file for record keeping in a real setup. You
will see that the Message Agent first receives a message from hq, and then
sends a message. This return message contains confirmation of successful
receipt of the replication update; such confirmations are part of the
SQL Remote message tracking system that ensures message delivery even in
the event of message system errors.
Verify that the data You should now connect to the remote field database using Interactive SQL,
has arrived and inspect the SalesRep and Customer tables, to see which rows have been
received.

v To verify that the data has arrived:


1 Connect to the field database using Interactive SQL.
2 Inspect the SalesRep table by executing the following statement:
SELECT * FROM SalesRep
You will see that the SalesRep table contains both rows entered at the
consolidated database. This is because the SalesRepData publication
included all the data from the SalesRep table.
3 Inspect the SalesRep table by executing the following statement:
SELECT * FROM Customer
You will also see that the Customer table contains only row (Ocean
Sports) entered at the consolidated database. This is because the
SalesRepData publication included only those customers assigned to
the subscribed Sales Rep.

Replicate from the remote database to the consolidated database


You should now try entering data at the remote database and sending it to the
consolidated database. Only the outlines are presented here.

265
Start replicating data

v To replicate data from the remote database to the consolidated


database:
1 Connect to the field database from Interactive SQL.
2 Insert a row at the remote database by executing the following
statement:
INSERT INTO Customer (cust_key, name, rep_key)
VALUES (’cust3’, ’North Land Trading’, ’rep1’)
3 Commit the insertion by executing the following statement::
COMMIT;
4 With the field.db database running, run the dbremote utility from a
command line to send the message to the consolidated database.
dbremote -c "dbn=field;uid=dba;pwd=sql"
5 With the hq.db database running, run the dbremote utility from a
command line to receive the message at the consolidated database:
dbremote -c "dbn=hq;uid=dba;pwd=sql"
6 Connect to the consolidated database. Display the Customer table by
executing the following statement:
SELECT *
FROM Customer

cust_key name rep_key


cust1 Ocean Sports rep1
cust2 Sports Plus rep2
cust3 North Land Trading rep1

In this simple example, there is no protection against duplicate entries of


primary key values. SQL Remote does provide for such protection. For
information, see the chapters on SQL Remote Design.

266
CHAPTER 12 A Tutorial for Adaptive Server Anywhere Users

A sample publication
The command file salespub.sql contains a set of statements that creates a
publication on the sample database. This publication illustrates several of the
points of the tutorial, in more detail.

v To add the publication to the sample database:


1 Connect to the sample database from Interactive SQL.
2 In the SQL Statements pane, execute the following statement:
READ path\scripts\salespub.SQL, where path is your Adaptive Server
Anywhere installation directory.
The salespub.sql publication adds columns to some of the tables in the
sample database, creates a publication and subscriptions, and also adds
triggers to resolve update conflicts that may occur.

267
A sample publication

268
C H A P T E R 1 3

A Tutorial for Adaptive Server Enterprise


Users

About this chapter This chapter presents a tutorial in which you set up a simple SQL Remote
replication system between an Adaptive Server Enterprise database and an
Adaptive Server Anywhere database, from scratch.
Contents
Topic Page
Introduction 270
Setting up SQL Remote using Sybase Central 273
Setting up the consolidated database 276
Set up the remote database in Sybase Central 281
A tutorial using isql and ssxtract 283
Setting up the consolidated database 286
Start replicating data 292

269
Introduction

Introduction
This chapter presents a tutorial to lead you through setting up a SQL Remote
installation. The installation replicates data between an Adaptive Server
Enterprise database (the consolidated database) and an Adaptive Server
Anywhere database (the remote database).

Tutorial goals
In the tutorial you act as the system administrator of a consolidated Adaptive
Server Enterprise database, and set up a simple replication system. The
replication system consists of a simple sales database, with two tables.
The consolidated database holds all of the database, while the remote
database has all of one table, but only some of the rows in the other table.
The tutorial takes you through the following steps:
♦ Creating a consolidated database on your Adaptive Server Enterprise
server.
♦ Creating a file-sharing replication system with a single Adaptive Server
Anywhere remote database.
♦ Replicating data between the two databases.

The database
The tutorial uses a simple two-table database. One table holds information
about sales representatives, and the other about customers. The tables are
much simpler than you would use in a real database; this allows us to focus
just on those issues important for replication.
Database schema The database schema for the tutorial is illustrated in the figure.

Customer SalesRep
cust_key char(10) rep_key = rep_key char(5)
name char(40) rep_key name char(40)
rep_key char(5)

Features to note include the following:


♦ Each sales representative is represented by one row in the SalesRep
table.
♦ Each customer is represented by one row in the customer table.

270
Chapter 13 A Tutorial for Adaptive Server Enterprise Users

♦ Each customer is assigned to a single Sales representative, and this


assignment is built in to the database as a foreign key from the Customer
table to the SalesRep table. The relationship between the Customer table
and the SalesRep table is many-to-one.

The tables in the The tables are described in more detail as follows:
database
Table Description
SalesRep One row for each sales representative that works for the
company. The SalesRep table has the following columns:
♦ rep_key An identifier for each sales representative. This is
the primary key.
♦ name The name of each sales representative.
The SQL statement creating this table is as follows:
CREATE TABLE SalesRep (
rep_key CHAR(12) NOT NULL,
name CHAR(40) NOT NULL,
PRIMARY KEY (rep_key)
)
Customer One row for each customer that does business with the
company. The Customer table includes the following columns:
♦ cust_key An identifier for each customer. This is the
primary key.
♦ name The name of each customer.
♦ rep_key An identifier for the sales representative in a sales
relationship. This is a foreign key to the SalesRep table.

The SQL statement creating this table is as follows:


CREATE TABLE Customer (
cust_key CHAR(12) NOT NULL,
name CHAR(40) NOT NULL,
rep_key CHAR(12) NOT NULL,
FOREIGN KEY ( rep_key )
REFERENCES SalesRep (rep_key ),
PRIMARY KEY (cust_key)
)

Replication goals
The goals of the replication design are to provide each sales representative
with the following information:
♦ The complete SalesRep table.
♦ Those customers assigned to them.
271
Introduction

The tutorial describes how to meet this goal using SQL Remote.
Use Sybase The tutorial material is presented twice. One section describes how to set up
Central or the the installation using the Sybase Central management utility. The second
command line section describes how to set up the installation using the Adaptive Server
Enterprise and Adaptive Server Anywhere interactive SQL utilities: this
requires typing commands individually.
Where next? ♦ To work through the tutorial using Sybase Central, go to "Setting up
SQL Remote using Sybase Central" on page 273.
♦ To work through the tutorial entering commands explicitly, go to "A
tutorial using isql and ssxtract" on page 283.

272
Chapter 13 A Tutorial for Adaptive Server Enterprise Users

Setting up SQL Remote using Sybase Central


The following sections are a tutorial describing how to set up a simple
SQL Remote replication system using Sybase Central.
You do not need to enter SQL statements if you are using Sybase Central to
administer SQL Remote. A tutorial for those who do not have access to
Sybase Central, who prefer to use command-line utilities, or who wish to
understand the individual commands executed, is presented in "A tutorial
using isql and ssxtract" on page 283. The commands described in that section
are executed behind the scenes by Sybase Central.

First steps
Create a login To work through the tutorial, you must have system administrator privileges
name and on an Adaptive Server Enterprise server. The tutorial assumes that your login
password name is the two-letter word sa and that this login name has a password of
sysadmin.
Create a database Create a database named hq on your Adaptive Server Enterprise with
sufficient space to hold the tables and data required by the tutorial database.
A space of 10 Mb is sufficient.

v To create a database from Sybase Central:


1 Connect to the Adaptive Server Enterprise from Sybase Central.
2 Open the Databases folder, and double-click Add database in the right
pane.
3 Enter the name hq on the first page of the wizard.
4 Follow the instructions in the wizard.
$ For information on how to create databases and assign space to them,
see your Adaptive Server Enterprise documentation.
Install You need to install SQL Remote into the hq database.
SQL Remote
v To install SQL Remote into the HQ database:
1 Open the hq database container, on the left pane of Sybase Central.
2 Open the SQL Remote folder, double-click Setup SQL Remote, and
follow the instructions. For this tutorial, you should install the stable
queue in the hq database.

273
Setting up SQL Remote using Sybase Central

If your TEMPDB database is too small, you may have to add space to it
for this to work.
$ For a full description of how to install SQL Remote, see "Setting Up
SQL Remote" on page 233.
Create directories Make a directory for the files created in this tutorial. For example:
for messages mkdir c:\tutorial
You should create a directory for each of the two users of the replication
system under your tutorial directory:
mkdir c:\tutorial\hq
mkdir c:\tutorial\field
The next step is to add a pair of tables to the consolidated database.

v To add tables to the consolidated database:


1 Connect to the hq database from Sybase Central, as a system
administrator.
2 Click the User Tables folder of the hq database.
3 Double-click Add Table, and use the Table Editor to create a table
named SalesRep with the following columns:

Key Column Data Type Size/Prec


Primary key rep_key char 5
name char 40

You do not need to use the Advanced Properties window. The columns
are created by default not allowing NULL.
4 Double-click Add Table again, and use the Table Editor to create a table
named Customer with the following columns:

Key Column Data Type Size/Prec


Primary key cust_key char 10
name char 40
rep_key char 5

Again, you do not need to use the Advanced Properties window. The
columns are created by default not allowing NULL.

274
Chapter 13 A Tutorial for Adaptive Server Enterprise Users

5 Open the Foreign Keys folder of the Customer table container, and
double-click Add Foreign Key. Using the wizard, add a foreign key to
the rep_key column of the SalesRep table. You can use the default
settings for this foreign key.
You are now ready for the rest of the tutorial.

275
Setting up the consolidated database

Setting up the consolidated database


This section of the tutorial describes how to prepare the consolidated
database of a simple replication system.
Preparing a consolidated database for replication involves the following
steps:
1 Create a message type to use for replication.
2 Grant PUBLISH permissions to a user ID to identify the source of
outgoing messages.
3 Grant REMOTE permissions to all user IDs that are to receive messages.
4 Create a publication describing the data to be replicated.
5 Create subscriptions describing who is to receive the publication.
You should have system administrator authority to carry out these tasks.

Add a SQL Remote message type


All messages sent as part of replication use a message type. A message type
description has two parts:
♦ A message link supported by SQL Remote. In this tutorial, we use the
FILE link.
♦ An address for this message link, to identify the source of outgoing
messages.
Adaptive Server Enterprise databases already have message types created
once you install SQL Remote into the database, but you need to supply an
address for the message type you will use.

v To add an address to a message type:


1 From Sybase Central, open the hq database container.
2 Click the SQL Remote folder on the left panel.
3 Double-click the Message Types folder on the right panel.
4 Double-click the file message type.
5 Enter a publisher address to provide a return address for remote users.
Enter hq; the directory you have created to hold messages for the
consolidated database.

276
Chapter 13 A Tutorial for Adaptive Server Enterprise Users

The address (hq) for a file link is a directory in which files containing
the message are placed. It is taken relative to the SQLRemote
environment variable or registry entry. As you have not set this value,
the address is taken relative to the directory from which the Message
Agent is run. You should run the Message Agent from your tutorial
directory for the addresses to be interpreted properly.
$ For information about setting the SQLRemote value, see "Setting
message type control parameters" on page 445.
6 Click OK to save the message type.

Create the necessary users and permissions


A set of users and permissions are required for SQL Remote installations. In
this tutorial, the following are required:
♦ A publisher user name.
♦ A remote user or subscriber.
This section describes the steps you need to take to create each user and
assign them the necessary permissions.

v To create the publisher:


1 From Sybase Central, open the container for the hq database.
2 Open the Users folder, and double-click Add User.
3 Create a user named hq_user, mapping the login name to an available
login name on your server. In this tutorial, a password of hq_pwd is
assumed.
4 Make this user the publisher of the HQ database. Open the SQL Remote
folder, and double-click Set Publisher. Select hq_user from the list of
users to set it as the publisher.
A database can have only one publisher. You can find out who the publisher
is at any time by opening the SQL Remote folder.
Add a remote user Each remote database is identified in the consolidated database by a user ID
with REMOTE permissions. Whether the remote database is a personal
server or a network server with many users, it needs a single user ID to
represent it to the consolidated database.
In a mobile workgroup setting, remote users may already be users of the
consolidated database, and so no new users would need to be added;
although they would need to be set as remote users.

277
Setting up the consolidated database

When a remote user is added to a database, the message system they use and
their address under that message system need to be stored along with their
database user ID.

v To add a remote user:


1 Double click the SQL Remote folder on the left panel, then click the
Remote Users folder on the left panel.
2 If you do not have a login name that you can use for the remote user,
open the logins folder directly under the server container, and add a
login. The name is unimportant.
Double-click Add Remote User on the right panel. The New Remote
User wizard is displayed.
3 Create a remote user with name field_user. For the message type and
address, select the FILE type and the corresponding address you are
using for this user (such as field).
As with the publisher address, the address of the remote user (field) is a
directory relative to the SQLRemote environment variable or registry
entry. As you have not set this value, the address is taken relative to the
directory from which the Message Agent is run. You should run the
Message Agent from your tutorial directory for the addresses to be
interpreted properly.
$ For information about setting the SQLRemote value, see "Setting
message type control parameters" on page 445.
4 On the next page, ensure that the Send Then Close option is checked. (In
many production environments you would not choose Send Then Close,
but it is convenient for this tutorial.)
5 When you have finished all the entries, click Finish to create the remote
user.
You have now created the users who will use this system.

Create the publication and subscription


This section describes how to add a publication to a database, and how to add
a subscription to that publication for a user. The publication replicates all
rows of the table SalesRep and some of the rows of the Customer table.
The first step is to mark the SalesRep and Customer tables for SQL Remote
replication. Marking a table for SQL Remote replication enables it to be
included in publications.

278
Chapter 13 A Tutorial for Adaptive Server Enterprise Users

v To mark the tables for SQL Remote replication:


1 Open the SQL Remote folder in the hq database.
2 Open the Remote Tables folder, and double-click Add Remote Table.
3 Select SalesRep from the list of tables. You can leave the Conflict
Resolution fields as they are. Click OK to mark the table for
SQL Remote replication.
4 Re-open the Table properties window. Select Customer from the list of
tables. Again, you can leave the Conflict Resolution fields as they are.
Click OK to mark the table for SQL Remote replication.

v To add a publication:
1 Click the Publications folder in the SQL Remote folder.
2 Double-click Add Publication. The Publication wizard is displayed.
3 Name the publication SalesRepData on the first page of the wizard.
4 On the next page, click Add Table and select SalesRep from the list.
Leave All Columns selected, and press OK to add the table.
Then click Add Table again, and select Customer from the list. Again,
leave All Columns selected. Click the Subscribe Restriction tab, and
choose to Subscribe by the column rep_key. Click OK to add the table
to the publication.
5 Complete the wizard to create the publication.

Add a subscription Each user ID that is to receive changes to a publication must have a
subscription to that publication. Subscriptions can only be created for a
valid remote user. You need to add a subscription to the SalesRepData
publication for the remote database user field_user.

v To add a subscription:
1 Double-click the Publications folder, which is in the SQL Remote
folder, so that the SalesRepData publication is displayed in the left
panel.
2 Click the Remote Users folder so that remote users are displayed in the
right panel.
3 Drag the field_user user from the right panel onto the SalesRepData
publication in the left panel. The Create Subscription window is
displayed. Enter a value of rep1 in the With Value box. The value rep1
is the rep_key value we will give to the user field_user in the SalesRep
table.

279
Setting up the consolidated database

At this stage, the subscription is not started—that is, no data will be


exchanged. The subscription is started by the database extraction utility.
You have now set up the consolidated database.

280
Chapter 13 A Tutorial for Adaptive Server Enterprise Users

Set up the remote database in Sybase Central


The remote database needs to be created and configured in order to send and
receive messages and participate in a SQL Remote setup.
Like the consolidated database, the remote database needs a publisher (in this
case, the field_user user ID) to identify the source of outgoing messages,
and it needs to have hq_user identified as a user with consolidated
permissions. It needs the SalesRepData publication to be created and needs
a subscription created for the hq_user user ID.
The remote database also needs to be synchronized with the consolidated
database; that is, it needs to have a current copy of the data in order for the
replication to start. In this case, there is no data in the publication as yet.
The database extraction utility enables you to carry out all the steps needed
to create a remote database complete with subscriptions and required user
IDs.
You need to extract a database from the consolidated database for remote
user field_user.

v To extract a database:
1 Click the Remote Users folder, which is in the SQL Remote folder.
2 Right-click the field_user remote user, and select Extract Database from
the popup menu. The Extraction wizard is displayed.
3 Use the user ID and password that you have used to create the tables and
users in the database.
4 On the next page, check Start Subscriptions Automatically, for user
field_user. Also, check Create New Remote Database. Adaptive Server
Anywhere must be installed for Create New Remote Database to be
available.
5 Create the database as file c:\tutorial\field.db, using a transaction log in
the same directory.
6 Choose to extract all parts of the schema (the default setting). Leave the
other options at their default settings, and create the remote database.
You should connect to the field database as DBA and confirm that all the
database objects are created.

v To connect to and inspect the remote database:


1 From Sybase Central, choose Tools➤Connect➤Sybase Adaptive Server
Anywhere.

281
Set up the remote database in Sybase Central

2 Provide the user ID DBA and the password SQL. These must be typed in
upper case, as the database was created as case sensitive. Select the
field.db file, and connect.
3 Open the database container, and confirm that the tables and user names
are present.
In a proper SQL Remote setup, the remote database field would need to be
loaded on to the computer using it, together with an Adaptive Server
Anywhere server and any client applications required. For this tutorial, we
leave the database where it is and use isql to input and replicate data.
What next? The system is now ready for replication.
$ For the next step, inserting and replicating data, see the section "Start
replicating data" on page 292.

282
Chapter 13 A Tutorial for Adaptive Server Enterprise Users

A tutorial using isql and ssxtract


The following sections are a tutorial describing how to set up a simple
SQL Remote replication system. This version of the tutorial does not use
Sybase Central.
This tutorial describes the stored procedures used to configure and manage
SQL Remote. It also describes how to run the ssxtract command-line utility
to extract remote databases from a consolidated database and the Message
Agents to send information between the databases in the replication system.
In this tutorial you act as the administrator of the consolidated database, and
set up a simple replication system using the file-sharing message link. The
simple example is a primitive model for a sales-force automation system,
with two tables. One contains a list of sales representatives, and another a list
of customers. The tables are replicated in a setup with one consolidated
database and one remote database. You can install this example on one
computer.

First steps
Create a login To work through the tutorial, you must have system administrator privileges
name and on an Adaptive Server Enterprise server. The tutorial assumes that your login
password name is the two-letter word sa and that your password is sysadmin.
The tutorial uses the Adaptive Server Enterprise isql utility. With the login
name and password as given above, you can connect to your Adaptive Server
Enterprise server using the following command line:
isql -S server-name -U sa -P sysadmin
where server-name is the name of the Adaptive Server Enterprise to which
you connect.
Ensure that you have an appropriate login ID and can connect to your server
before starting this tutorial.
Create a database Create a database named hq on your Adaptive Server Enterprise server with
sufficient space to hold the tables and data required by the tutorial database.
A space of 4 Mb is sufficient.

v To create a database:
1 Using isql, connect to the server as a user with system administrator
privileges:
isql -S server-name -U sa -P sysadmin
2 Use the master database:
283
A tutorial using isql and ssxtract

use master
go
3 Create a database named hq. In this example, we use a 5 Mb database
with a 5 Mb log, on two different devices:
create database hq
on database_device = 5
log on log_device = 5
go

$ For more information on how to create databases and assign space to


them, see your Adaptive Server Enterprise documentation.
Install You need to install SQL Remote into the hq database.
SQL Remote
v To install SQL Remote into the hq database:
1 If the system administrator login name you are using does not have the
hq database as the default database, make a backup copy of the
ssremote.sql script from your installation directory, and add the
following two lines to the beginning of the script:
use hq
go
2 Change to the tutorial directory. Then, using isql, connect to the server
using the hq database, and run the ssremote.sql script from your
SQL Remote installation directory. The following command should be
entered all on one line:
isql -S server-name -U sa -P sysadmin -i
ssremote.sql
3 If the system administrator login name you are using does not have the
hq database as the default database, make a backup copy of the
stableq.sql script from your installation directory, and add the following
two lines to the beginning of the script:
use hq
go
4 Using isql, connect to the server using the hq database, and run the
stableq.sql script from your SQL Remote installation directory. The
following command should be entered all on one line:
isql -S server-name -U sa -P sysadmin -i stableq.sql

Create directories Create a directory to hold the files from this tutorial. For example:
for messages mkdir c:\tutorial
You should create a directory for each of the two users of the replication
system under your parent directory for this tutorial:

284
Chapter 13 A Tutorial for Adaptive Server Enterprise Users

mkdir c:\tutorial\hq
mkdir c:\tutorial\field
The next step is to add a pair of tables to the consolidated database.

v To add tables to the consolidated database:


1 Connect to the hq database from isql, as a system administrator.
2 Use the hq database:
use hq
go
3 Create the SalesRep table with the following statement:
create table SalesRep (
rep_key char(12) not null,
name char(40) not null,
primary key (rep_key) )
go
4 Create the Customer table with the following statement:
create table Customer (
cust_key char(12) not null,
name char(40) not null,
rep_key char(12) not null,
primary key (cust_key) )
go
5 Alter the Customer table to add a foreign key to the SalesRep table:
alter table Customer
add foreign key
( rep_key ) references SalesRep
go

You are now ready for the rest of the tutorial.

285
Setting up the consolidated database

Setting up the consolidated database


This section of the tutorial describes how to prepare the consolidated
database of a simple replication system.
Preparing a consolidated database for replication involves the following
steps:
1 Create a message type to use for replication.
2 Grant PUBLISH permissions to a user ID to identify the source of
outgoing messages.
3 Grant REMOTE permissions to all user IDs that are to receive messages.
4 Create a publication describing the data to be replicated.
5 Create subscriptions describing who is to receive the publication.
You should have system administrator authority to carry out these tasks.

Create the message links and addresses


In this tutorial, messages are exchanged using the shared file link. You must
create a FILE message type supplying the address of the consolidated
database publisher.

v To create the message type:


♦ Execute the sp_remote_type stored procedure, using HQ as the address
of the consolidated database publisher:
sp_remote_type file, hq
go
The address (hq) for a file link is a directory in which files containing
the message are placed. It is taken relative to the SQLRemote
environment variable or registry entry. As you have not set this value,
the address is taken relative to the directory from which the Message
Agent is run. You should run the Message Agent from your tutorial
directory for the addresses to be interpreted properly.
$ For information about setting the SQLRemote value, see "Setting
message type control parameters" on page 445.
With the message type defined, you can now make the necessary users.

286
Chapter 13 A Tutorial for Adaptive Server Enterprise Users

Create the necessary users and permissions


A set of users and permissions are required for SQL Remote installations. In
this tutorial, the following are required:
♦ A remote user or subscriber, with name field_user.
♦ A publisher user name, called hq_user.
This section describes the steps you need to take to create each user and
assign them the necessary permissions.

v To create the publisher:


1 Add a login called hq_user, with hq as the default database and with
system administrator access:
exec sp_addlogin hq_user, hq_pwd, hq
go
exec sp_role ’grant’, sa_role, hq_user
go
2 Add the login name as a user to the HQ database:
use hq
go
exec sp_adduser hq_user
go
3 Make this user the publisher of the HQ database:
exec sp_publisher hq_user
go

Add a remote user Each remote database is identified in the consolidated database by a user ID
with REMOTE permissions. Whether the remote database is a single-user
server or a database server with many users, it needs a single user ID to
represent it to the consolidated database.
In a mobile workgroup setting, remote users may already be users of the
consolidated database, and so no new users would need to be added;
although they would need to be set as remote users.
When a remote user is added to a database, the message system they use and
their address under that message system need to be stored along with their
database user ID.

v To create the subscriber:


1 If you do not have a login name that you can use for the remote user,
add a login:
exec sp_addlogin field_user, field_pwd, hq

287
Setting up the consolidated database

go
2 Add a user to the hq database:
exec sp_adduser field_user
go
3 Grant the user remote permissions. Execute the sp_grant_remote stored
procedure, using field_user as the user name, file as the message type,
and the appropriate directory as the address:
exec sp_grant_remote field_user, file, field
go
As with the publisher address, the address of the remote user (field) is a
directory relative to the SQLRemote environment variable or registry
entry. As you have not set this value, the address is taken relative to the
directory from which the Message Agent is run. You should run the
Message Agent from your tutorial directory for the addresses to be
interpreted properly.
$ For information about setting the SQLRemote value, see "Setting
message type control parameters" on page 445.

Create the publication and subscription


The remaining task is to define the data to be replicated. To do this, you must
first create a publication, which defines the available data, and then create a
subscription for field_user, which defines the data that user is sharing.
In Adaptive Server Enterprise, they are created with the
sp_create_publication procedure, which creates an empty publication, and
the sp_add_article procedure, which adds articles to the procedure. Also,
each table must be marked for replication before it can be included in a
publication.

v To create the publication:


1 Create an empty publication:
exec sp_create_publication SalesRepData
go
2 Mark both the SalesRep table and the Customer table for publication:
exec sp_add_remote_table SalesRep
go
exec sp_add_remote_table Customer
go
3 Add the whole SalesRep table to the SalesRepData publication:

288
Chapter 13 A Tutorial for Adaptive Server Enterprise Users

exec sp_add_article SalesRepData, SalesRep


go
4 Add the Customer table to the SalesRepData publication, using the
rep_key column to partition the table. The following statement should
be typed all on one line, except for the go:
exec sp_add_article SalesRepData, Customer, NULL,
’rep_key’
go

Add a subscription Each user ID that is to receive changes to a publication must have a
subscription to that publication. Subscriptions can only be created for a
valid remote user. You need to add a subscription to the SalesRepData
publication for the remote database user field_user.

v To create a subscription:
1 Create a subscription to SalesRepData for field_user, with a
subscription value of rep1:
exec sp_subscription ’create’, SalesRepData,
field_user, ’rep1’
go
At this stage, the subscription is not started—that is, no data will be
exchanged. The subscription is started by the database extraction utility.

Extract the remote database


There are three stages to producing a remote Adaptive Server Anywhere
database:
♦ Extract the schema and data into a set of files. You do this using the
ssxtract command-line utility.
♦ Create an Adaptive Server Anywhere database.
♦ Load the schema and data into the database.

Extracting the With all the information included, the next step is to extract an Adaptive
schema and data Server Anywhere database for user field_user. The following command line
(entered all on one line, from the tutorial directory) carries out this
procedure:
ssxtract -v -c "eng=server-name;
dbn=hq;uid=sa;pwd=sysadmin" C:\tutorial\field field_user
The command-line arguments have the following meaning.

289
Setting up the consolidated database

♦ -v Verbose mode. For development work, this provides additional


output.
♦ -c Connection string argument. The connection string is supplied in
double quotes following the -c.
♦ eng=server-name Specifies the server to which the extraction utility
is to connect.
♦ dbn=hq Specifies the database on the server to use; in this case hq.
♦ uid=sa The login ID to use to log on to the database.
♦ pwd=sysadmin The password to use to log on to the database.
♦ C:\tutorial\field The directory in which to place files holding the data.
♦ field_user The user ID for which to extract the database.
$ For more information on extraction utility command-line switches, see
"The extraction command-line utility" on page 532
Running this command produces the following files:
♦ Reload script The reload script is named reload.sql, and is placed in
the current directory.
♦ Data files Files containing data to load into the database. In this case,
these files are empty.

Creating an You can create an Adaptive Server Anywhere database using the dbinit
Adaptive Server command-line utility. A simple Adaptive Server Anywhere database is a file,
Anywhere unlike Adaptive Server Enterprise databases.
database
You should create the Adaptive Server Anywhere database so that it is
compatible with Adaptive Server Enterprise database behavior, unless you
have set options in your Adaptive Server Enterprise server that are different
from the default.

v To create a database file named field.db:


♦ Enter the following command from the c:\tutorial\field directory:
dbinit -b -c -k field.db

The -b switch forces use of blank padding in string comparisons. The -c


switch enforces case sensitivity for string comparisons. The -k switch
makes the system catalog more compatible with Adaptive Server
Enterprise.

290
Chapter 13 A Tutorial for Adaptive Server Enterprise Users

Loading the data You can load the data into the database using the Adaptive Server Anywhere
into the database Interactive SQL utility or the rtsql command-line utility. rtsql is an alternative
to Interactive SQL for batch processes only, and is provided for the runtime
database.

v To load the data into the database using Interactive SQL:


1 Start an Adaptive Server Anywhere server running on the field database:
dbeng7 field.db
2 Connect to the server using the Interactive SQL utility:
dbisql -c "eng=field;dbn=field;uid=DBA;pwd=SQL"
The user ID and password must be entered in upper case, as the
Adaptive Server Anywhere database was created as case-sensitive.
3 Load the data using the READ command:
READ C:\TUTORIAL\RELOAD.SQL

v To load the data into the database as a batch process:


1 Start an Adaptive Server Anywhere server running on the field database:
dbeng7 field.db
2 Run the script from Interactive SQL:
dbisql -c "eng=field;dbn=field;uid=DBA;pwd=SQL"
reload.sql
The user ID and password must be entered in upper case, as the
Adaptive Server Anywhere database was created as case-sensitive.

What next? The system is now ready for replication.


$ For the next step, inserting and replicating data, see the section "Start
replicating data" on page 292.

291
Start replicating data

Start replicating data


You now have a replication system in place. In this section, data is replicated
from the consolidated database to the remote database, and from the remote
to the consolidated database.

Enter data at the consolidated database


In this section we enter data into the SalesRep and Customer tables at the
consolidated (Adaptive Server Enterprise) database, and replicate this data to
the Adaptive Server Anywhere database.

v To enter data at the Adaptive Server Enterprise database:


1 Connect to the Adaptive Server Enterprise server from isql:
isql -S server-name -U sa -P sysadmin
2 Ensure you are using the hq database, and enter a series of rows:
use hq
go
insert into SalesRep (rep_key, name)
values (’rep1’, ’Field User’)
go
insert into SalesRep (rep_key, name)
values (’rep2’, ’Another User’)
go
insert into Customer (cust_key, name, rep_key)
values (’cust1’, ’Ocean Sports’, ’rep1’)
go
insert into Customer (cust_key, name, rep_key)
values (’cust2’, ’Sports Plus’, ’rep2’)
go
commit
go
Ocean Sports is assigned to Field User, and Sports Plus is assigned to
Another User. You must commit the changes, as SQL Remote
replicates only committed changes.
Having entered the data at the consolidated database, you now need to send
the relevant rows to the remote Adaptive Server Anywhere database.

292
Chapter 13 A Tutorial for Adaptive Server Enterprise Users

Send data from the consolidated database


To send the rows to the remote database, you must run the Message Agent at
the consolidated database. The ssremote program is the Message Agent for
Adaptive Server Enterprise.

v To replicate the data from Adaptive Server Enterprise:


♦ Enter the following statement (on a single line) at the command line to
run the Message Agent against the consolidated database:
ssremote -c "eng=server-
name;dbn=hq;uid=sa;pwd=sysadmin"
3 Click Shutdown on the Message Agent window to stop the Message
Agent when the messages have been sent.

Receive data at the remote database


To receive the insert statement at the remote database, you must run the
Message Agent, dbremote, at the remote database.

v To receive the data at Adaptive Server Anywhere:


1 With the database server running, receive the data using the Message
Agent for Adaptive Server Anywhere:
dbremote -c "eng=field;dbn=field;uid=DBA;pwd=SQL"

$ For more information on dbremote command line switches, see


"The Message Agent" on page 522.
2 Click Shutdown on the Message Agent window to stop the Message
Agent when the messages have been processed.
The Message Agent window displays status information while running. This
information can be output to a log file for record keeping in a production
setup.
The Message Agent first receives a message from hq, and then sends a
message. This return message contains confirmation of successful receipt of
the replication update; such confirmations are part of the SQL Remote
message tracking system that ensures message delivery even in the event of
message system errors.
Verify that the data You should now connect to the remote field database using Interactive SQL,
has arrived and inspect the SalesRep and Customer tables, to see which rows have been
received.

293
Start replicating data

v To verify that the data has arrived:


1 Connect to the field database using Interactive SQL.
2 Inspect the SalesRep table by typing the following statement:
SELECT * FROM SalesRep
You will see that the SalesRep table contains both rows entered at the
consolidated database. This is because the SalesRepData publication
included all the data from the SalesRep table.
3 Inspect the Customer table by typing the following statement:
SELECT * FROM Customer
You will see that the Customer table contains only one row (Ocean
Sports) entered at the consolidated database. This is because the
SalesRepData publication included only those customers assigned to
the subscribed Sales Rep.

Replicate from the remote database to the consolidated database


You should now try entering data at the remote database and sending it to the
consolidated database. Only the outlines are presented here.

v To replicate data from the remote database to the consolidated


database:
1 Connect to the field database from Interactive SQL.
2 INSERT a row at the remote database. For example
INSERT INTO Customer (cust_key, name, rep_key)
VALUES (’cust3’, ’North Land Trading’, ’rep1’)
3 COMMIT the row.:
COMMIT;
4 With the field.db database running, run dbremote to send the message to
the consolidated database.
dbremote -c "eng=field;dbn=field;uid=DBA;pwd=SQL"
(For Windows 3.x, run the dbremotw equivalent.)
5 Run ssremote to receive the message at the consolidated database:
ssremote -c "eng=server-
name;dbn=hq;uid=sa;pwd=sysadmin"
6 Connect to the consolidated database and display the Customer table.
This now has three rows:

294
Chapter 13 A Tutorial for Adaptive Server Enterprise Users

SELECT *
FROM Customer

cust_key name rep_key


cust1 Ocean Sports rep1
cust2 Sports Plus rep2
cust3 North Land Trading rep1

In this simple example, there is no protection against duplicate entries of


primary key values. SQL Remote does provide for such protection. For
information, see the chapters on SQL Remote Design.

295
Start replicating data

296
C H A P T E R 1 4

Principles of SQL Remote Design

About this chapter This chapter describes general issues and principles for designing a
SQL Remote installation.
$ For system-specific details, see the chapters "SQL Remote Design for
Adaptive Server Enterprise" on page 369 and "SQL Remote Design for
Adaptive Server Anywhere" on page 315.
Contents
Topic Page
Design overview 298
How statements are replicated 302
How data types are replicated 307
Who gets what? 310
Replication errors and conflicts 312

297
Design overview

Design overview
This chapter describes general publication design issues that you must
address when designing a SQL Remote installation. It also describes how
SQL Remote replicates data.
Design at the Like all SQL Remote administrative tasks, design is carried out by a database
consolidated administrator or system administrator at the consolidated database.
database
The Adaptive Server Enterprise System Administrator or database
administrator should perform all SQL Remote configuration tasks.

Ensuring compatible databases


You should ensure that all databases participating in a SQL Remote
installation are compatible in terms of sort orders, character sets, and
database option settings.
If your installation includes both Adaptive Server Enterprise and Adaptive
Server Anywhere databases, you should ensure your Adaptive Server
Anywhere databases are created in an Adaptive Server Enterprise-compatible
fashion.
$ For a full description of how to create Enterprise-compatible Adaptive
Server Anywhere databases, see "Creating a Transact-SQL-compatible
database", in the chapter "Using Transact-SQL with Adaptive Server
Anywhere", in the Adaptive Server Anywhere User’s Guide. This section
provides a brief description only.

v To create an Enterprise-compatible Adaptive Server Anywhere


database using Sybase Central:
♦ The Create Database wizard provides an button that sets each of the
available choices to emulate Adaptive Server Enterprise. This is the
simplest way to create a Transact-SQL-compatible database.

v To create an Enterprise-compatible Adaptive Server Anywhere


database from the command line:
1 Ensure trailing blanks are ignored You can do this using the dbinit
-b command-line switch.
2 Ensure the dbo user ID is set If you have a database that already has
a user ID named dbo, then you can transfer the ownership of the
Adaptive Server Anywhere Transact-SQL system views to another user
ID. You can do this using the dbinit -g command-line switch.

298
Chapter 14 Principles of SQL Remote Design

3 Remove historical system views You can do this with the dbinit -k
command-line switch.
4 Make the database case sensitive You can do this with the dbinit -c
command-line switch.
The following command creates a case-sensitive database named test.db in
the current directory, using the current dbo user, ignoring trailing blanks, and
removing historical system views:
dbinit -b -c -k test.db

Using compatible sort orders and character sets


The SQL Remote Message Agent does not perform any character set
conversions.
Character sets in For an Adaptive Server Anywhere installation, the character set and collation
Adaptive Server used by the consolidated database must be the same as the remote databases.
Anywhere For information about supported character sets, see "International Languages
installations and Character Sets" on page 279 of the book ASA User’s Guide.
Character sets in The Open Client/Open Server libraries perform character set conversions
Adaptive Server between SSREMOTE and Adaptive Server Enterprise whenever the
Enterprise LOCALES.DAT character set is different from the Adaptive Server
installations Enterprise character set. Both character sets must be installed on the
Adaptive Server Enterprise server and conversion must be supported.
Character sets in The locales.dat settings (which are used by all Open Client applications)
mixed installations must match the remote Adaptive Server Anywhere settings.
The following table provides recommended matches between Adaptive
Server Enterprise and Adaptive Server Anywhere character sets. The
matches are not all complete.

Adaptive Open Client / Open Client / Open Client /


Server Open Server Open Server case- Open Server
Anywhere name sensitive sort case-
collation order insensitive
name sort order
default cp850 dictionary_cp850 nocase_cp850
850 cp850 dictionary_cp850 nocase_cp850
437 cp437 dictionary_cp437 nocase_cp437
852 cp852 bin_cp852 bin_cp852
860 cp860 bin_cp860 bin_cp860
437LATIN1 cp437 dictionary_cp437 nocase_cp437

299
Design overview

Adaptive Open Client / Open Client / Open Client /


Server Open Server Open Server case- Open Server
Anywhere name sensitive sort case-
collation order insensitive
name sort order
437ESP cp437 espdict_cp437 espnocs_cp437
437SVE cp437 bin_cp437 bin_cp437
819CYR iso_1 bin_iso_1 bin_iso_1
819DAN iso_1 bin_iso_1 bin_iso_1
819ELL iso_1 bin_iso_1 bin_iso_1
819ESP iso_1 espdict_iso_1 espnocs_iso_1
819ISL iso_1 bin_iso_1 bin_iso_1
819LATIN1 iso_1 dictionary_iso_1 nocase_iso_1
819LATIN2 iso_1 bin_iso_1 bin_iso_1
819NOR iso_1 bin_iso_1 bin_iso_1
819RUS iso_1 bin_iso_1 bin_iso_1
819SVE iso_1 bin_iso_1 bin_iso_1
819TRK iso_1 bin_iso_1 bin_iso_1
850CYR cp850 bin_cp850 bin_cp850
850DAN cp850 scandict_cp850 scannocp_cp85
0
850ELL cp850 bin_cp850 bin_cp850
850ESP cp850 espdict_cp850 espnocs_cp850
850ISL cp850 scandict_cp850 scannocp_cp85
0
850LATIN1 cp850 dictionary_cp850 nocase_cp850
850LATIN2 cp850 bin_cp850 bin_cp850
850NOR cp850 scandict_cp850 scannocp_cp85
0
850RUS cp850 bin_cp850 bin_cp850
850SVE cp850 scandict_cp850 scannocp_cp85
0
850TRK cp850 bin_cp850 bin_cp850
852LATIN2 cp852 bin_cp852 bin_cp852
852CYR cp852 bin_cp852 bin_cp852

300
Chapter 14 Principles of SQL Remote Design

Adaptive Open Client / Open Client / Open Client /


Server Open Server Open Server case- Open Server
Anywhere name sensitive sort case-
collation order insensitive
name sort order
855CYR cp855 cyrdict_cp855 cynocs_cp855
857TRK cp857 bin_cp857 bin_cp857
860LATIN1 cp860 bin_cp860 bin_cp860
866RUS cp866 rusdict_cp866 rusnocs_cp866
869ELL cp869 bin_cp869 bin_cp869
SJIS sjis bin_sjis bin_sjis
SJIS2 sjis bin_sjis bin_sjis
EUC_JAPAN eucjis bin_eucjis bin_eucjis
EUC_CHINA eucgb bin_eucgb bin_eucgb
EUC_TAIWAN eucb5 bin_big5 bin_big5
EUC_KOREA eucksc bin_eucksc bin_eucksc
UTF8 utf8 bin_utf8 bin_utf8

301
How statements are replicated

How statements are replicated


SQL Remote replication is based on the transaction log, enabling it to
replicate only changes to data, rather than all data, in each update. When we
say that SQL Remote replicates data, we really mean that SQL Remote
replicates SQL statements that modify data.
Only committed SQL Remote replicates only statements in committed transactions, to ensure
transactions are proper transaction atomicity throughout the replication setup and maintain a
replicated consistency among the databases involved in the replication, albeit with
some time lag while the data is replicated.
Primary keys When an UPDATE or a DELETE is replicated, SQL Remote uses the
primary key columns to uniquely identify the row being updated or deleted.
All tables being replicated must have a declared primary key or uniqueness
constraint. A unique index is not sufficient. The columns of the primary key
are used in the WHERE clause of replicated updates and deletes. If a table
has no primary key, the WHERE clause refers to all columns in the table.
An UPDATE is not When a simple INSERT statement is entered at one database, it is sent to
always an other databases in the SQL Remote setup as an INSERT statement. However,
UPDATE not all statements are replicated exactly as they are entered by the client
application. This section describes how SQL Remote replicates SQL
statements. It is important to understand this material if you are to design a
robust SQL Remote installation.
The Message Agent is the component that carries out the replication of
statements.

Replication of inserts and deletes


INSERT and DELETE statements are the simplest replication case.
SQL Remote takes each INSERT or DELETE operation from the transaction
log, and sends it to all sites that subscribe to the row being inserted or
deleted.
If only a subset of the columns in the table is subscribed to, the INSERT
statements sent to subscribers contains only those columns.
The Message Agent ensures that statements are not replicated to the user that
initially entered them.

302
Chapter 14 Principles of SQL Remote Design

Replication of updates
UPDATE statements are not replicated exactly as the client application
enters them. This section describes two ways in which the replicated
UPDATE statement may differ from the entered UPDATE statement.
UPDATE If an UPDATE statement has the effect of removing a row from a given
statements remote user’s subscription, it is sent to that user as a DELETE statement. If
replicated as an UPDATE statement has the effect of adding a row to a given remote
INSERTS or user’s subscription, it is sent to that user as an INSERT statement.
DELETES
The figure illustrates a publication, where each subscriber subscribes by their
name:

Consolidated Ann Marc


ID Rep Dept ID Rep ID Rep
1 Ann 101 1 Ann 2 Marc
2 Marc 101 3 Marc
3 Marc 101

Consolidated Ann Marc


ID Rep Dept ID Rep ID Rep
1 Ann 101 1 Ann 2 Marc
2 Marc 101 > 3 Ann 3 Marc
3 Ann 101
An UPDATE that changes the Rep value of a row from Marc to Ann is
replicated to Marc as a DELETE statement, and to Ann as an INSERT
statement.
This reassignment of rows among subscribers is sometimes called territory
realignment, because it is a common feature of sales force automation
applications, where customers are periodically reassigned among
representatives.
UPDATE conflict An UPDATE statement changes the value of one or more rows from some
detection existing value to a new value. The rows altered depend on the WHERE
clause of the UPDATE statement.
When SQL Remote replicates an UPDATE statement, it does so as a set of
single-row updates. These single-row statements can fail for one of the
following reasons:

303
How statements are replicated

♦ The row to be updated does not exist Each row is identified by its
primary key values, and if a primary key has been altered by some other
user, the row to be updated is not found.
In this case, the UPDATE does not update anything.
♦ The row to be updated differs in one or more of its columns If one
of the values expected to be present has been changed by some other
user, an update conflict occurs.
At remote databases, the update takes place regardless of the values in
the row.
At the consolidated database, SQL Remote allows conflict resolution
operations to take place. Conflict resolution operations are held in a
trigger or stored procedure, and run automatically when a conflict is
detected.
In Adaptive Server Anywhere, the conflict resolution trigger runs before
the update, and the update .proceeds when the trigger is finished. In
Adaptive Server Enterprise, the conflict resolution procedure runs after
the update has been applied.
♦ A table without a primary key or uniqueness constraint refers to all
columns in the WHERE clause of replicated updates When two
users update the same row, replicated updates will not update anything
and databases will become inconsistent. All replicated tables should
have a primary key or uniqueness constraint and the columns in the
constraint should never be updated.

Replication of procedures
Any replication system is faced with a choice between two options when
replicating a stored procedure call:
♦ Replicate the procedure call A corresponding procedure is executed
at the replicate site, or
♦ Replicate the procedure actionsThe individual actions (INSERTs,
UPDATEs, DELETEs and so on) of the procedure are replicated.
SQL Remote replicates procedures by replicating the actions of a procedure.
The procedure call is not replicated.

304
Chapter 14 Principles of SQL Remote Design

Replication of triggers
Trigger replication in SQL Remote is different for the Adaptive Server
Enterprise Message Agent and the Adaptive Server Anywhere Message
Agent.
Trigger replication From Adaptive Server Enterprise, trigger actions are replicated. You must
from Adaptive ensure that triggers are not fired in the remote Adaptive Server Anywhere
Server Enterprise databases. If the trigger were fired, its actions would be executed twice.
The Adaptive Server Anywhere FIRE_TRIGGERS database option prevents
triggers from being fired. If you set this option for the user ID used by the
Message Agent, be careful to not use this user ID for other purposes.

An alternative approach to preventing trigger execution, available only for


Adaptive Server Anywhere, is to use the following condition around the
body of your triggers:
IF CURRENT REMOTE USER IS NULL

This make execution conditional on whether the current user is the Message
Agent.
Trigger replication By default, the Message Agent for Adaptive Server Anywhere does not
from Adaptive replicate actions performed by triggers; it is assumed that the trigger is
Server Anywhere defined remotely. This avoids permissions issues and the possibility of each
action occurring twice. There are some exceptions to this rule:
♦ Conflict resolution trigger actions The actions carried out by
conflict resolution, or RESOLVE UPDATE, triggers are replicated from
a consolidated database to all remote databases, including the one that
sent the message causing the conflict.
♦ Replication of BEFORE triggers Some BEFORE triggers can
produce undesirable results when using SQL Remote, and so BEFORE
trigger actions that modify the row being updated are replicated, before
UPDATE actions.
You must be aware of this behavior when designing your installation.
For example, a BEFORE UPDATE that bumps a counter column in the
row to keep track of the number of times a row is updated would double
count if replicated, as the BEFORE UPDATE trigger will fire when the
UPDATE is replicated. To prevent this problem, you must ensure that, at
the subscriber database, the trigger is not present or does not carry out
the replicated action. Also, a BEFORE UPDATE that sets a column to
the time of the last update will get the time the UPDATE is replicated as
well.

305
How statements are replicated

An option to The Adaptive Server Anywhere Message Agent has a command-line switch
replicate trigger that causes it to replicate all trigger actions when sending messages. This is
actions the dbremote -t switch.

If you use this switch, you must ensure that the trigger actions are not carried
out twice at remote databases, once by the trigger being fired at the remote
site, and once by the explicit application of the replicated actions from the
consolidated database.

To ensure that trigger actions are not carried out twice, you can wrap an IF
CURRENT REMOTE USER IS NULL ... END IF statement around the
body of the triggers or you can set the Adaptive Server Anywhere
Fire_triggers option to OFF for the Message Agent user ID.

Replication of data definition statements


Data definition statements (CREATE, ALTER, DROP, and others that
modify database objects) are not replicated by SQL Remote unless they are
entered while in passthrough mode.
$ For information about passthrough mode for Adaptive Server
Anywhere, see "Using passthrough mode" on page 489.

306
Chapter 14 Principles of SQL Remote Design

How data types are replicated


Long binary or character data, and datetime data, need special consideration.

Replication of blobs
Blobs are LONG VARCHAR, LONG BINARY, TEXT, and IMAGE data
types: values that are longer than 256 characters.
Adaptive Server SQL Remote includes a special method for replicating blobs between
Anywhere Adaptive Server Anywhere databases.
replication
The Message Agent uses a variable in place of the value in the INSERT or
UPDATE statement that is being replicated. The value of the variable is built
up by a sequence of statements of the form
SET vble = vble || ’more_stuff’
This makes the size of the SQL statements involving long values smaller, so
that they fit within a single message. The SET statements are separate SQL
statements, so that the blob is effectively split over several SQL Remote
messages.
Adaptive Server Blobs can be replicated to and from Adaptive Server Enterprise as long as
Enterprise they fit into the Message Agent memory.
replication
Sybase Open Client CTLIB applications that manipulate the CS_IODESC
structure must not set the log_on_update member to FALSE.

Using the The Verify_threshold database option can prevent long values from being
Verify_threshold verified (in the VERIFY clause of a replicated UPDATE). The default value
option to minimize for the option is 1000. If the data type of a column is longer than the
message size threshold, old values for the column are not verified when an UPDATE is
replicated. This keeps the size of SQL Remote messages down, but has the
disadvantage that conflicting updates of long values are not detected.
There is a technique allowing detection of conflicts when Verify_threshold
is being used to reduce the size of messages. Whenever a "blob" is updated, a
last_modified column in the same table should also be updated. Conflicts
can then be detected because the old value of the last_modified column is
verified.
Using a work table Repeated updates to a blob should be done in a "work" table, and the final
to avoid redundant version should be assigned to the replicated table. For example, if a
updates document in progress is updated 20 times throughout the day and the
Message Agent is run once at the end of the day, all 20 updates are
replicated. If the document is 200 kb in length, this causes 4 Mb of messages
to be sent.

307
How data types are replicated

The better solution is to have a document_in_progress table. When the user


is done revising a document, the application moves it from the
document_in_progress table to the replicated table. The results in a single
update (200 kb of messages).
Controlling The Adaptive Server Anywhere BLOB_THRESHOLD option allows further
replication of blobs control over the replication of long values. Any value longer than the
BLOB_THRESHOLD option is replicated as a blob. That is, it is broken into
pieces and replicated in chunks, before being reconstituted by using a SQL
variable and concatenating the pieces at the recipient site.
By setting BLOB_THRESHOLD to a high value in remote Adaptive Server
Anywhere databases, blobs are not broken into pieces, and operations can be
applied to Adaptive Server Enterprise by the Message Agent. Each SQL
statement must fit within a message, so this only allows replication of small
blobs.

Replication of dates and times


When date or time columns are replicated, the Message Agent uses the
setting of the SR_Date_Format, SR_Time_Format, and
SR_Timestamp_Format database options to format the date.
For example, the following option setting instructs the Message Agent to
send a date of May 2, 1987 as 1987-05-02.
SET OPTION SR_Date_Format = ’yyyy-mm-dd’
$ For more information, see "SQL Remote options" on page 542.
The following points may be useful when replicating dates and times:
♦ The time, date, and timestamp formats must be consistent throughout the
installation.
♦ If the consolidated database is an Adaptive Server Anywhere database,
ensure that the order of year, month, and day used for the date and
timestamp formats matches the setting of the DATE_ORDER database
option.
You can change the DATE_ORDER option for the duration of each
connection.
♦ If the consolidated database is an Adaptive Server Enterprise database,
ensure that the order of year, month, and day in the SQL Remote
settings is consistent with the dateformat setting in the Adaptive Server
Enterprise database.

308
Chapter 14 Principles of SQL Remote Design

v To find the dateformat settings on an Adaptive Server Enterprise


database:
1 Login to the Adaptive Server Enterprise database from isql using the
login ID used by ssremote. In this example, we use ssr for this login ID.
2 Issue the following command:
select *
from master..syslogins
where name = ’ssr’
go
Adaptive Server Enterprise returns the default language for the ssr user.
3 If ssr uses the default language (us_english) then the default dateformat
is YMD. If the language is different from the default, enter the following
command:
sp_helplanguage language-name
where language-name is the language in use by the ssr user. The
information displayed includes the default date format for the language.

309
Who gets what?

Who gets what?


Each time a row in a table is inserted, deleted, or updated, a message has to
be sent to those subscribed to the row. In addition, an update may cause the
subscription expression to change, so that the statement is sent to some
subscribers as a delete, some as an update, and some as an insert.
$ For details of what statements get sent to which subscribers, see "How
statements are replicated" on page 302. For details on subscriptions, see the
following two chapters.
This section describes how SQL Remote sends the right operations to the
right recipients.
The task of determining who gets what is divided between the database
server and the Message Agent. The engine handles those aspects that are to
do with publications, while the Message Agent handles aspects to do with
subscriptions.
Adaptive Server Adaptive Server Anywhere evaluates the subscription expression for each
Anywhere actions update made to a table that is part of a publication. It adds the value of the
expression to the log, both before and after the update.

Not the subscriber list


Adaptive Server Enterprise does not evaluate or enter into the log a list of
subscribers. The subscription expression (a property of the publication) is
evaluated and entered. All handling of subscribers is left to the Message
Agent.

For a table that is part of more than one publication, the subscription
expression is evaluated before and after the update for each publication.
The addition of information to the log can affect performance in the
following cases:
♦ Expensive expressions When a subscription expression is expensive
to evaluate, it can affect performance.
♦ Many publications When a table belongs to many publications, many
expressions must be evaluated. In contrast, the number of subscriptions
is irrelevant.
♦ Many-valued expressions Some expressions are many-valued. This
can lead to much additional in formation in the transaction log, with a
corresponding effect on performance.

310
Chapter 14 Principles of SQL Remote Design

Adaptive Server In a SQL Remote for Adaptive Server Enterprise publication, the
Enterprise actions subscription expression must be a column. The subscription column contains
either a single value or a comma-separated list of values.

Not the subscriber list


Adaptive Server Enterprise does not enter into the log a list of subscribers.
The column value is entered. All handling of subscribers is left to the
Message Agent.

When a table is marked for replication using sp_add_remote_table (which


calls sp_setreplicate), Adaptive Server Enterprise places an entire before
image of the row in the transaction log for deletes, and entire after image for
inserts, and both images for updates. This means that the before and after
values of the subscription column are available.
Message Agent The Message Agent reads the evaluated subscription expressions or
actions subscription column entries from the transaction log, and matches the before
and after values against the subscription value for each subscriber to the
publication. In this way, the Message Agent can send the correct operations
to each subscriber.
While large numbers of subscribers do not have any impact on server
performance, they can impact Message Agent performance. Both the work in
matching subscription values against large numbers of subscription values,
and the work in sending the messages, can be demanding.

311
Replication errors and conflicts

Replication errors and conflicts


SQL Remote is designed to allow databases to be updated at many different
sites. Careful design is required to avoid replication errors, especially if the
database has a complicated structure. This section describes the kinds of
errors and conflict that can occur in a replication setup; subsequent sections
describe how you can design your publications to avoid errors and manage
conflicts.

Delivery errors not discussed here


This section does not discuss issues related to message delivery failures.
For information on delivery errors and how they are handled, see "The
message tracking system" on page 467

Replication errors
Replication errors fall into the following categories:
♦ Duplicate primary key errors Two users INSERT a row using the
same primary key values, or one user updates a primary key and a
second user inserts a primary key of the new value. The second
operation to reach a given database in the replication system fails
because it would produce a duplicate primary key.
♦ Row not found errors A user DELETES a row (that is, the row with a
given primary key value). A second user UPDATES or DELETES the
same row at another site.
In this case, the second statement fails, as the row is not found.
♦ Referential integrity errors If a column containing a foreign key is
included in a publication, but the associated primary key is not included,
the extraction utility leaves the foreign key definition out of the remote
database so that INSERTS at the remote database will not fail.
This can be solved by including proper defaults into the table
definitions.
Also, referential integrity errors can occur when a primary table has a
SUBSCRIBE BY expression and the associated foreign table does not:
rows from the foreign table may be replicated, but the rows from the
primary table may be excluded from the publication.

312
Chapter 14 Principles of SQL Remote Design

Replication conflicts
Replication conflicts are different from errors. Properly handled, conflicts are
not a problem in SQL Remote.
♦ Conflicts A user updates a row. A second user updates the same row
at another site. The second user’s operation succeeds, and SQL Remote
allows a trigger to be fired (Adaptive Server Anywhere) or a procedure
to be called (Adaptive Server Enterprise) to resolve these conflicts in a
way that makes sense for the data being changed.
Conflicts will occur in many installations. SQL Remote allows
appropriate resolution of conflicts as part of the regular operation of a
SQL Remote setup, using triggers and procedures.
$ For information about how SQL Remote handles conflicts as they
occur, see the following chapters.

Tracking SQL errors


SQL errors in replication must be designed out of your setup. SQL Remote
includes an option to help you track errors in SQL statements, but this option
is not intended to resolve such errors.

By setting the Replication_error option, you can specify a stored procedure


to be called by the Message Agent when a SQL error occurs. By default no
procedure is called.

v To set the Replication_error option in Adaptive Server Anywhere:


♦ Issue the following statement:
SET OPTION
remote-user.Replication_error
= ’procedure-name’
where remote-user is the user ID on the Message Agent command line,
and procedure-name is the procedure called when a SQL error is
detected.

v To set the Replication_error option in Adaptive Server Enterprise:


♦ Issue the following statement:
exec sp_remote_option Replication_error, procedure-
name
go

313
Replication errors and conflicts

where procedure-name is the procedure called when a SQL error is


detected.

Replication error The replication error procedure must have a single argument of type CHAR,
procedure VARCHAR, or LONG VARCHAR. The procedure is called once with the
requirements SQL error message and once with the SQL statement that causes the error.

314
C H A P T E R 1 5

SQL Remote Design for Adaptive Server


Anywhere

About this chapter This chapter describes how to design a SQL Remote installation when the
consolidated database is an Adaptive Server Anywhere database.

Similar material for Adaptive Server Enterprise


Many of the principles of publication design are the same for Adaptive
Server Anywhere and Adaptive Server Enterprise, but there are
differences in commands and capabilities. There is a large overlap
between this chapter and the corresponding chapter for Adaptive Server
Enterprise users, "SQL Remote Design for Adaptive Server Enterprise" on
page 369.

Contents
Topic Page
Design overview 316
Creating publications 317
Publication design for Adaptive Server Anywhere 327
Partitioning tables that do not contain the subscription expression 330
Sharing rows among several subscriptions 338
Managing conflicts 347
Ensuring unique primary keys 357
Creating subscriptions 366

315
Design overview

Design overview
Designing a SQL Remote installation includes the following tasks:
♦ Designing publications The publications determine what information
is shared among which databases.
♦ Designing subscriptions The subscriptions determine what
information each user receives.
♦ Implementing the design Creating publications and subscriptions for
all users in the system.

All administration is Like all SQL Remote administrative tasks, design is carried out by a database
at the consolidated administrator or system administrator at the consolidated database.
database
The Adaptive Server Anywhere Database Administrator should perform all
SQL Remote configuration tasks.

316
Chapter 15 SQL Remote Design for Adaptive Server Anywhere

Creating publications
This section describes how to create simple publications consisting of whole
tables, or of column-wise subsets of tables; these tables are also called
articles. You can perform these tasks using Sybase Central or with the
CREATE PUBLICATION statement in Interactive SQL.
All publications in Sybase Central appear in the Publications folder (located
within the SQL Remote folder). Any articles you create for that publication
appear within the publication container. With Sybase Central, you do not
need to know the SQL syntax in order to create publications or articles.
$ Simple publications are also discussed in the chapter "A Tutorial for
Adaptive Server Anywhere Users" on page 241.

Publishing a whole table


The simplest publication you can make consists of a single article, which
consists of a single, entire table.

v To create a publication that includes all the rows and columns of a


single table (Sybase Central):
1 Open the Publications folder (located within the SQL Remote folder).
2 Double-click Add Publication.
3 On the first page of the wizard, type a name for the publication and click
Next.
4 Click Add Table.
5 At the top of the resulting dialog, choose a table to represent the article.
6 Select the All columns option.
7 Click OK and follow the rest of the instructions in the wizard.

v To create a publication that includes all the rows and columns of a


single table (SQL):
1 Connect to a database with DBA authority.
2 Execute a CREATE PUBLICATION statement that specifies the name
of the publication and the table you want to publish.
Example ♦ The following statement creates a publication that publishes the whole
customer table:
CREATE PUBLICATION pub_customer (

317
Creating publications

TABLE customer
)

$ See also
♦ "CREATE PUBLICATION statement" on page 579
♦ "Altering existing publications" on page 324

Publishing some of the columns in a table


You can create a publication that contains only some of the columns of a
table. An article that contains only some of the columns of a table is called a
column-wise partitioning of the table. An article that contains only some of
the rows of a table is called a row-wise partitioning of the table; for more
information about row-wise partitioning, see "Publishing some of the rows
from a table" on page 320. Articles can be both column-wise and row-wise
partitions of a table.
You create a publication that contains all the rows, but only some of the
columns, of a table in Sybase Central or by specifying a list of columns in
the CREATE PUBLICATION statement.

v To create a publication that includes all the rows and some of the
columns of a table (Sybase Central):
1 Open the Publications folder (located within the SQL Remote folder).
2 Double-click Add Publication.
3 On the first page of the wizard, type a name for the publication and click
Next.
4 Click Add Table.
5 At the top of the resulting dialog, choose a table to represent the article.
6 Select the Only these columns option and choose the columns you want
included in the article.
7 Click OK and follow the rest of the instructions in the wizard.

v To create a publication that includes all the rows and some of the
columns of a table (SQL):
1 Connect to a database with DBA authority.
2 Execute a CREATE PUBLICATION statement that specifies the
publication name, the table name, and the names of the columns.

318
Chapter 15 SQL Remote Design for Adaptive Server Anywhere

Example ♦ The following statement creates a publication that publishes all rows of
the id, company_name, and city columns of the customer table:
CREATE PUBLICATION pub_customer (
TABLE customer (
id,
company_name,
city )
)

$ See also
♦ "CREATE PUBLICATION statement" on page 579
♦ "Conditions for valid articles" on page 328
♦ "Altering existing publications" on page 324

Publishing a set of tables


When you publish a set of tables, a separate article is required for each table
in the publication. You can use Sybase Central for this task, or you can
specify a set of tables in a CREATE PUBLICATION statement.

v To create a publication that includes a set of tables (Sybase


Central):
1 Open the Publications folder (located within the SQL Remote folder).
2 Double-click Add Publication.
3 On the first page of the wizard, type a name for the publication and click
Next.
4 Click Add Table.
5 In the resulting dialog, configure the desired values for that table. Click
OK to exit the dialog and return to the wizard.
6 Continue to click Add Table in the wizard, configuring new articles each
time, until you have included all the tables you want in the publication.
7 Follow the rest of the instructions in the wizard.

v To create a publication that includes a set of tables (SQL):


1 Connect to a database with DBA authority.
2 Execute a CREATE PUBLICATION statement that specifies the
publication name and the tables involved.

319
Creating publications

Example ♦ The following statement creates a publication including all columns and
rows in each of a set of tables from the Adaptive Server Anywhere
sample database:
CREATE PUBLICATION sales (
TABLE customer,
TABLE sales_order,
TABLE sales_order_items,
TABLE product
)

Not all the tables in the database have been published. For example,
subscribers receive the sales_order table, but not the employee table.
Notes ♦ In the sample database, the sales_order and employee tables are related
by a foreign key (sales_rep in the sales_order table is a foreign key to
the emp_id column in the employee table). Although this could lead to
referential integrity problems in the remote database, they are easily
avoided by using the database extraction utility.
♦ A slightly different publication design (including an article that contains
enough of the employee table to satisfy the foreign key relationship)
would make the publication more robust; for this section we are
publishing whole tables only.
$ See also
♦ "CREATE PUBLICATION statement" on page 579
♦ "Designing to avoid referential integrity errors" on page 355
♦ "Altering existing publications" on page 324

Publishing some of the rows from a table


There are two ways of including only some of the rows in a publication:
♦ WHERE clause You can use a WHERE clause to include a subset of
rows in an article. All subscribers to the publication containing this
article receive the rows that satisfy the WHERE clause.
♦ Subscription expression You can use a subscription expression to
include a different set of rows in different subscriptions to publications
containing the article.
You can combine a WHERE clause and a subscription expression in an
article. You can specify them in Sybase Central or in a CREATE
PUBLICATION statement.

320
Chapter 15 SQL Remote Design for Adaptive Server Anywhere

Use the Subscription expression when different subscribers to a publication


are to receive different rows from a table. The Subscription expression is the
most powerful method of partitioning tables.
Use the WHERE clause to exclude the same set of rows from all
subscriptions to a publication.

Publishing a subset of rows using a WHERE clause


You can specify a WHERE clause to include in the publication only the rows
that satisfy the WHERE conditions.

v To create a publication using a WHERE clause (Sybase Central):


1 Open the Publications folder (located within the SQL Remote folder).
2 Double-click Add Publication.
3 On the first page of the wizard, type a name for the publication and click
Next.
4 Click Add Table.
5 On the Table tab of the resulting dialog, configure the desired values for
that table.
6 On the Where restriction tab of the dialog, enter the WHERE clause.
When finished, click OK to exit the dialog and return to the wizard.
7 Follow the rest of the instructions in the wizard.

v To create a publication using a WHERE clause (SQL):


1 Connect to a database with DBA authority.
2 Execute a CREATE PUBLICATION statement that includes the rows
you wish to include in the publication and a WHERE condition.
Examples ♦ The following statement creates a publication that publishes the id,
company_name, city, and state columns of the customer table, for the
customers marked as active in the status column.
CREATE PUBLICATION pub_customer (
TABLE customer (
id,
company_name,
city,
state )
WHERE status = ’active’
)

321
Creating publications

In this case, the status column is not included in the publication. It must
therefore have a default value so that inserts at remote databases will not
fail at the consolidated database.
♦ The following is a single-article publication sending relevant order
information to Samuel Singer, a sales rep:
CREATE PUBLICATION pub_orders_samuel_singer (
TABLE sales_order WHERE sales_rep = 856
)

$ See also
♦ "CREATE PUBLICATION statement" on page 579
♦ "Altering existing publications" on page 324
♦ "Publishing a subset of rows using a subscription expression" on
page 322

Publishing a subset of rows using a subscription expression


You can specify a subscription expression to include a different set of rows
in different subscriptions to publications containing the article.
For example, in a mobile workforce situation, a sales publication may be
wanted where each sales rep subscribes to their own sales orders, enabling
them to update their sales orders locally and replicate the sales to the
consolidated database.
Using the WHERE clause model, a separate publication for each sales rep
would be needed: the following publication is for sales rep Samuel Singer:
each of the other sales reps would need a similar publication.
CREATE PUBLICATION pub_orders_samuel_singer (
TABLE sales_order
WHERE sales_rep = 856
)
To address the needs of setups requiring large numbers of different
subscriptions, SQL Remote allows a subscription expression to be
associated with an article. Subscriptions receive rows depending on the value
of a supplied expression.
Benefits of Publications using a subscription expression are more compact, easier to
subscription understand, and provide better performance than maintaining several
expressions WHERE clause publications. The database server must add information to
the transaction log, and scan the transaction log to send messages, in direct
proportion to the number of publications. The subscription expression allows
many different subscriptions to be associated with a single publication,
whereas the WHERE clause does not.

322
Chapter 15 SQL Remote Design for Adaptive Server Anywhere

v To create an article using a subscription expression (Sybase


Central):
1 Open the Publications folder (located within the SQL Remote folder).
2 Double-click Add Publication.
3 On the first page of the wizard, type a name for the publication and click
Next.
4 Click Add Table.
5 On the Table tab of the resulting dialog, configure the desired values for
that table.
6 On the Subscribe restriction tab of the dialog, use the controls to create
the subscription expression. When finished, click OK to exit the dialog
and return to the wizard.
7 Follow the rest of the instructions in the wizard.

v To create an article using a subscription expression (SQL):


1 Connect to a database with DBA authority.
2 Execute a CREATE PUBLICATION statement that includes the
expression you wish to use as a match in the subscription expression.
Examples ♦ The following statement creates a publication that publishes the id,
company_name, city, and state columns of the customer table, and
which matches the rows with subscribers according to the value of the
state column:
CREATE PUBLICATION pub_customer (
TABLE customer (
id,
company_name,
city,
state )
SUBSCRIBE BY state
)
♦ The following statements subscribe two employees to the publication:
Ann Taylor receives the customers in Georgia (GA), and Sam Singer
receives the customers in Massachusetts (MA).
CREATE SUBSCRIPTION
TO pub_customer (’GA’)
FOR Ann_Taylor ;
CREATE SUBSCRIPTION
TO pub_customer (’MA’)
FOR Sam_Singer

323
Creating publications

Users can subscribe to more than one publication, and can have more than
one subscription to a single publication.
$ See also
♦ "CREATE PUBLICATION statement" on page 579
♦ "Partitioning tables that do not contain the subscription expression" on
page 330
♦ "Creating subscriptions" on page 366
♦ "Publishing a subset of rows using a WHERE clause" on page 321
♦ "Altering existing publications" on page 324

Altering existing publications


After you have created a publication, you can alter it by adding, modifying,
or deleting articles, or by renaming the publication. If an article is modified,
the entire specification of the modified article must be entered.
You can perform these tasks using Sybase Central or with the ALTER
PUBLICATION statement in Interactive SQL.

v To modify the properties of existing publications or articles (Sybase


Central):
1 Right-click the publication or article and choose Properties from the
popup menu.
2 Configure the desired properties.

v To add articles (Sybase Central):


1 Open the Publications folder (located within the SQL Remote folder).
2 Open the publication container.
3 Double-click Add Article.
4 In the New Article dialog, do the following:
♦ On the Tables tab, choose a table and the number of columns.
♦ On the Where restriction tab, enter a WHERE clause (if desired).
♦ On the Subscribe restriction tab, create a subscription expression (if
desired).
5 Click OK to create the article.

324
Chapter 15 SQL Remote Design for Adaptive Server Anywhere

v To remove articles (Sybase Central):


1 Open the Publications folder (located within the SQL Remote folder).
2 Open the publication container.
3 Right-click the article you want to delete and choose Delete from the
popup menu.

v To modify an existing publication (SQL):


1 Connect to a database with DBA authority.
2 Execute an ALTER PUBLICATION statement.
Example ♦ The following statement adds the customer table to the pub_contact
publication.
ALTER PUBLICATION pub_contact (
ADD TABLE customer
)

$ See also
♦ "ALTER PUBLICATION statement" on page 577
♦ "Publishing a subset of rows using a WHERE clause" on page 321
♦ "Publishing a subset of rows using a subscription expression" on
page 322
♦ For a description of all property sheets in Sybase Central, see "Property
Sheet Descriptions" on page 1035 of the book ASA User’s Guide.

Dropping publications
You can drop a publication using either Sybase Central or the DROP
PUBLICATION statement. If you drop a publication, all subscriptions to that
publication are automatically deleted as well.
You must have DBA authority to drop a publication.

v To delete a publication (Sybase Central):


1 Open the Publications folder (located within the SQL Remote folder).
2 Right-click the desired publications and choose Delete from the popup
menu.

325
Creating publications

v To delete a publication (SQL):


1 Connect to a database.
2 Execute a DROP PUBLICATION statement.

Example The following statement drops the publication named pub_orders.


DROP PUBLICATION pub_orders

$ See also
♦ "DROP PUBLICATION statement" on page 587

Notes on publications
♦ The different publication types described above can be combined. A
single publication can publish a subset of columns from a set of tables,
and use both a WHERE clause to select a set of rows to be replicated
and a subscription expression to partition rows by subscription.
♦ DBA authority is required to create publications.
♦ Publications can be altered and dropped only by the DBA.
♦ Altering publications in a running SQL Remote setup is likely to cause
replication errors, and could lead to loss of data in the replication system
unless carried out with care.
♦ Views cannot be included in publications.
♦ Stored procedures cannot be included in publications. For a discussion
of how SQL Remote replicates procedures and triggers, see "Replication
of procedures" on page 304 .
♦ For other considerations of referential integrity, see the section
"Designing to avoid referential integrity errors" on page 355.

326
Chapter 15 SQL Remote Design for Adaptive Server Anywhere

Publication design for Adaptive Server


Anywhere
Once you understand how to create simple publications, you must think
about proper publication design. Sound design is an important part of
building a successful SQL Remote installation. This section helps set out the
principles of sound design as they apply to SQL Remote for Adaptive Server
Anywhere.

Similar material for Adaptive Server Enterprise


Many of the principles of publication design are the same for Adaptive
Server Anywhere and Adaptive Server Enterprise, but there are
differences in commands and capabilities. There is a large overlap
between this section and the corresponding section for Adaptive Server
Enterprise users, "Publication design for Adaptive Server Enterprise" on
page 376.

Design issues overview


Each subscription A remote database shares with the consolidated database the information in
must be a their subscriptions. The subscription is both a subset of the relational
complete relational database held at the consolidated site, and also a complete relational database
database at the remote site. The information in the subscription is therefore subject to
the same rules as any other relational database:
♦ Foreign key relationships must be valid For every entry in a foreign
key, a corresponding primary key entry must exist in the database.
The database extraction utility ensures that the CREATE TABLE
statements for remote databases do not have foreign keys defined to
tables that do not exist remotely.
♦ Primary key uniqueness must be maintained There is no way of
checking what new rows have been entered at other sites, but not yet
replicated. The design must prevent users at different sites adding rows
with identical primary-key values, as this would lead to conflicts when
the rows are replicated to the consolidated database.

Transaction The data in the dispersed database (which consists of the consolidated
integrity must be database and all remote databases) must maintain its integrity in the face of
maintained in the updates at all sites, even though there is no system-wide locking mechanism
absence of locking for any particular row.

327
Publication design for Adaptive Server Anywhere

♦ Locking conflicts must be prevented or resolved In a SQL Remote


installation, there is no method for locking rows across all databases to
prevent different users from altering the rows at the same time. Such
conflicts must be prevented by designing them out of the system or must
be resolved in an appropriate manner at the consolidated database.
These key features of relational databases must be incorporated into the
design of your publications and subscriptions. This section describes
principles and techniques for sound design.

Conditions for valid articles


All columns in the primary key must be included in the article.
Supporting For INSERT statements at a remote database to replicate correctly to the
INSERTS at consolidated database, you can exclude from an article only columns that can
remote databases be left out of a valid INSERT statement. These are:
♦ Columns that allow NULL.
♦ Columns that have defaults.
If you exclude any column that does not satisfy one of these requirements,
INSERT statements carried out at a remote database will fail when replicated
to the consolidated database.

Consolidated ID Rep Dept


INSERT 1 Ann 101
INTO SalesRep (ID, Rep) Insert fails
VALUES (3, ’Shih’ ) 2 Marc 101
3 Shih X

Remote ID Rep
INSERT 1 Ann Insert
INTO SalesRep (ID, Rep)
VALUES (3, ’Shih’ ) 2 Marc succeeds
3 Shih

328
Chapter 15 SQL Remote Design for Adaptive Server Anywhere

Using BEFORE triggers as an alternative


An exception to this case is when the consolidated database is an
Adaptive Server Anywhere database, and a BEFORE trigger has been
written to maintain the columns that are not included in the INSERT
statement.

Design tips for performance


This section presents a check list for designing high performance
SQL Remote installations.
♦ Keep the number of publications small In particular, try not to
reference the same table in many different publications.
The work the database server needs to do is proportional to the number
of publications. Keeping the number low and making effective use of
subscriptions lightens the load on the database server.
When operations occur on a table, the database server and the Message
Agent must do some work for each publication that contains the table.
Having one publication for each remote user will drastically increase the
load on the database server. It is much better to have a few publications
that use SUBSCRIBE BY and have subscriptions for each remote user.
The database server does no additional work when more subscriptions
are added for a publication. The Message Agent is designed to work
efficiently with a large number of subscriptions.
♦ Group publications logically For example, if there is a table that
every remote user requires, such as a price list table, make a separate
publication for that table. Make one publication for each table where the
data can be partitioned by a column value.
♦ Use subscriptions effectively When remote users receive similar
subsets of the consolidated database, always use publications that
incorporate SUBSCRIBE BY expressions. Do not create a separate
publication for each remote user.
♦ Pay attention to Update Publication Triggers In particular:
♦ Use the NEW / OLD SUBSCRIBE BY syntax.
♦ Tune the SELECT statements to ensure they are accessing the
database efficiently.
♦ Monitor the transaction log size The larger the transaction log, the
longer it takes the Message Agent to scan it. Rename the log regularly
and use the DELETE_OLD_LOGS option.

329
Partitioning tables that do not contain the subscription expression

Partitioning tables that do not contain the


subscription expression
In many cases, the rows of a table need to be partitioned even when the
subscription expression does not exist in the table.

The Contact example


The Contact database illustrates why and how to partition tables that do not
contain the subscription expression.
Example Here is a simple database that illustrates the problem.

Contact
contact_key char(10)
name char(40)
cust_key char(12)

cust_key = cust_key

Customer
SalesRep
cust_key char(12) rep_key =
rep_key char(5)
name char(40) rep_key
name char(40)
rep_key char(5)

Each sales representative sells to several customers. At some customers there


is a single contact, while other customers have several contacts.
The tables in the The three tables are described in more detail as follows:
database

330
Chapter 15 SQL Remote Design for Adaptive Server Anywhere

Table Description
SalesRep All sales representatives that work for the company. The
SalesRep table has the following columns:
♦ rep_key An identifier for each sales representative. This is
the primary key.
♦ name The name of each sales representative.
The SQL statement creating this table is as follows:
CREATE TABLE SalesRep (
rep_key CHAR(12) NOT NULL,
name CHAR(40) NOT NULL,
PRIMARY KEY (rep_key)
)
Customer All customers that do business with the company. The Customer
table includes the following columns:
♦ cust_key An identifier for each customer. This is the primary
key.
♦ name The name of each customer.
♦ rep_key An identifier for the sales representative in a sales
relationship. This is a foreign key to the SalesRep table.

The SQL statement creating this table is as follows:


CREATE TABLE Customer (
cust_key CHAR(12) NOT NULL,
name CHAR(40) NOT NULL,
rep_key CHAR(12) NOT NULL,
FOREIGN KEY REFERENCES SalesRep,
PRIMARY KEY (cust_key)
)

331
Partitioning tables that do not contain the subscription expression

Table Description
Contact All individual contacts that do business with the company. Each
contact belongs to a single customer. The Contact table includes
the following columns:
♦ contact_key An identifier for each contact. This is the
primary key.
♦ name The name of each contact.
♦ cust_key An identifier for the customer to which the contact
belongs. This is a foreign key to the Customer table.

The SQL statement creating this table is:


CREATE TABLE Contact (
contact_key CHAR(12) NOT NULL,
name CHAR(40) NOT NULL,
cust_key CHAR(12) NOT NULL,
FOREIGN KEY REFERENCES Customer,
PRIMARY KEY (contact_key)
)

Replication goals The goals of the design are to provide each sales representative with the
following information:
♦ The complete SalesRep table.
♦ Those customers assigned to them, from the Customer table.
♦ Those contacts belonging to the relevant customers, from the Contact
table.

Partitioning the Customer table in the Contact example


The Customer table can be partitioned using the rep_key value as a
subscription expression. A publication that includes the SalesRep and
Customer tables would be as follows:
CREATE PUBLICATION SalesRepData (
TABLE SalesRep
TABLE Customer SUBSCRIBE BY rep_key
)

332
Chapter 15 SQL Remote Design for Adaptive Server Anywhere

Partitioning the Contact table in the Contact example


The Contact table must also be partitioned among the sales representatives,
but contains no reference to the sales representative rep_key value. How can
the Message Agent match a subscription value against rows of this table,
when rep_key is not present in the table?
To solve this problem, you can use a subquery in the Contact article that
evaluates to the rep_key column of the Customer table. The publication
then looks like this:
CREATE PUBLICATION SalesRepData (
TABLE SalesRep
TABLE Customer
SUBSCRIBE BY rep_key
TABLE Contact
SUBSCRIBE BY (SELECT rep_key
FROM Customer
WHERE Contact.cust_key = Customer.cust_key )
)
The WHERE clause in the subscription expression ensures that the subquery
returns only a single value, as only one row in the Customer table has the
cust_key value in the current row of the Contact table.
$ For an Adaptive Server Enterprise consolidated database, the solution
is different. For more information, see "Partitioning tables that do not contain
the subscription column" on page 378.

Territory realignment in the Contact example


In territory realignment, rows are reassigned among subscribers. In the
present case, territory realignment is the reassignment of rows in the
Customer table, and by implication also the Contact table, among the Sales
Reps.
When a customer is reassigned to a new sales rep, the Customer table is
updated. The UPDATE is replicated as an INSERT or a or a DELETE to the
old and new sales representatives, respectively, so that the customer row is
properly transferred to the new sales representative.
$ For information on the way in which Adaptive Server Anywhere and
SQL Remote work together to handle this situation, see "Who gets what?" on
page 310.

333
Partitioning tables that do not contain the subscription expression

When a customer is reassigned, the Contact table is unaffected. There are no


changes to the Contact table, and consequently no entries in the transaction
log pertaining to the Contact table. In the absence of this information,
SQL Remote cannot reassign the rows of the Contact table along with the
Customer.
This failure will cause referential integrity problems: the Contact table at the
remote database of the old sales representative contains a cust_key value for
which there is no longer a Customer.
Use triggers to The solution is to use a trigger containing a special form of UPDATE
maintain Contacts statement, which does not make any change to the database tables, but which
does make an entry in the transaction log. This log entry contains the before
and after values of the subscription expression, and so is of the proper form
for the Message Agent to replicate the rows properly.
The trigger must be fired BEFORE operations on the row. In this way, the
BEFORE value can be evaluated and placed in the log. Also, the trigger must
be fired FOR EACH ROW rather than for each statement, and the
information provided by the trigger must be the new subscription expression.
The Message Agent can use this information to determine which subscribers
receive which rows.
Trigger definition The trigger definition is as follows:
CREATE TRIGGER UpdateCustomer
BEFORE UPDATE ON Customer
REFERENCING NEW AS NewRow
OLD as OldRow
FOR EACH ROW
BEGIN
// determine the new subscription expression
// for the Customer table
UPDATE Contact
PUBLICATION SalesRepData
OLD SUBSCRIBE BY ( OldRow.rep_key )
NEW SUBSCRIBE BY ( NewRow.rep_key )
WHERE cust_key = NewRow.cust_key;
END;

A special UPDATE The UPDATE statement in this trigger is of the following special form:
statement for UPDATE table-name
publications PUBLICATION publication-name
{ SUBSCRIBE BY subscription-expression |
OLD SUBSCRIBE BY old-subscription-expression
NEW SUBSCRIBE BY new-subscription-expression }
WHERE search-condition
Here is what the UPDATE statement clauses mean:

334
Chapter 15 SQL Remote Design for Adaptive Server Anywhere

♦ The table-name indicates the table that must be modified at the remote
databases.
♦ The publication-name indicates the publication for which subscriptions
must be changed.
♦ The value of subscription-expression is used by the Message Agent to
determine both new and existing recipients of the rows. Alternatively,
you can provide both OLD and NEW subscription expressions.
♦ The WHERE clause specifies which rows are to be transferred between
subscribed databases.

Notes on the ♦ If the trigger uses the following syntax:


trigger UPDATE table-name
PUBLICATION pub-name
SUBSCRIBE BY sub-expression
WHERE search-condition
the trigger must be a BEFORE trigger. In this case, a BEFORE
UPDATE trigger. In other contexts, BEFORE DELETE and BEFORE
INSERT are necessary.
♦ If the trigger uses the alternate syntax:
UPDATE table-name
PUBLICATION publication-name
OLD SUBSCRIBE BY old-subscription-expression
NEW SUBSCRIBE BY new-subscription-expression }
WHERE search-condition
The trigger can be a BEFORE or AFTER trigger.
♦ The UPDATE statement lists the publication and table that is affected.
The WHERE clause in the statement describes the rows that are
affected. No changes are made to the data in the table itself by this
UPDATE, it makes entries in the transaction log.
♦ The subscription expression in this example returns a single value.
Subqueries returning multiple values can also be used. The value of the
subscription expression must the value after the UPDATE.
In this case, the only subscriber to the row is the new sales
representative. In "Sharing rows among several subscriptions" on
page 338, we see cases where there are existing as well as new
subscribers.
Information in the Here we describe the information placed in the transaction log.
transaction log Understanding this helps in designing efficient publications.
♦ Assume the following data:
♦ SalesRep table

335
Partitioning tables that do not contain the subscription expression

rep_key Name
rep1 Ann
rep2 Marc

♦ Customer table

cust_key name rep_key


cust1 Sybase rep1
cust2 ASA rep2

♦ Contact table

contact_key name cust_key


contact1 David cust1
contact2 Stefanie cust2

♦ Now apply the following territory realignment Update statement


UPDATE Customer
SET rep_key = ’rep2’
WHERE cust_key = ’cust1’
The transaction log would contain two entries arising from this
statement: one for the BEFORE trigger on the Contact table, and one for
the actual UPDATE to the Customer table.
SalesRepData – Publication Name
rep1 – BEFORE list
rep2 – AFTER list
UPDATE Contact
SET contact_key = 'contact1',
name = 'David',
cust_key = 'cust1'
WHERE contact_key = 'contact1'
SalesRepData – Publication Name
rep1 – BEFORE list
rep2 – AFTER list
UPDATE Customer
SET rep_key = 'rep2'
WHERE cust_key = 'cust1'
The Message Agent scans the log for these tags. Based on this
information it can determine which remote users get an INSERT,
UPDATE or DELETE.

336
Chapter 15 SQL Remote Design for Adaptive Server Anywhere

In this case, the BEFORE list was rep1 and the AFTER list is rep2. If
the before and after list values are different, the rows affected by the
UPDATE statement have "moved" from one subscriber value to another.
This means the Message Agent will send a DELETE to all remote users
who subscribed by the value rep1 for the Customer record cust1 and
send an INSERT to all remote users who subscribed by the value rep2.
If the BEFORE and AFTER lists are identical, the remote user already
has the row and an UPDATE will be sent.

337
Sharing rows among several subscriptions

Sharing rows among several subscriptions


There are cases where a row may need to be included in several
subscriptions. For example, we may have a many-to-many relationship. In
this section, we use a case study to illustrate how to handle this situation.

The Policy example


The Policy database illustrates why and how to partition tables when there is
a many-to-many relationship in the database.
Example database Here is a simple database that illustrates the problem.

Customer Policy SalesRep

cust_key policy_key rep_key

name cust_key name

rep_key

Each sales representative sells to several customers, and some customers deal
with more than one sales representative. In this case, the relationship
between Customer and SalesRep is thus a many-to-many relationship.
The tables in the The three tables are described in more detail as follows:
database

338
Chapter 15 SQL Remote Design for Adaptive Server Anywhere

Table Description
SalesRep All sales representatives that work for the company. The
SalesRep table has the following columns:
♦ rep_key An identifier for each sales representative. This is
the primary key.
♦ name The name of each sales representative.
The SQL statement creating this table is as follows:
CREATE TABLE SalesRep (
rep_key CHAR(12) NOT NULL,
name CHAR(40) NOT NULL,
PRIMARY KEY (rep_key)
);
Customer All customers that do business with the company. The
Customer table includes the following columns:
♦ cust_key A primary key column containing an identifier for
each customer
♦ name A column containing the name of each customer
The SQL statement creating this table is as follows:
CREATE TABLE Customer (
cust_key CHAR(12) NOT NULL,
name CHAR(40) NOT NULL,
PRIMARY KEY (cust_key)
);

339
Sharing rows among several subscriptions

Table Description
Policy A three-column table that maintains the many-to-many
relationship between customers and sales representatives. The
Policy table has the following columns:
♦ policy_key A primary key column containing an identifier
for the sales relationship.
♦ cust_key A column containing an identifier for the
customer representative in a sales relationship.
♦ rep_key A column containing an identifier for the sales
representative in a sales relationship.

The SQL statement creating this table is as follows.


CREATE TABLE Policy (
policy_key CHAR(12) NOT NULL,
cust_key CHAR(12) NOT NULL,
rep_key CHAR(12) NOT NULL,
FOREIGN KEY ( cust_key )
REFERENCES Customer ( cust_key )
FOREIGN KEY ( rep_key )
REFERENCES SalesRep (rep_key ),
PRIMARY KEY ( policy_key )
);

Replication goals The goals of the replication design are to provide each sales representative
with the following information:
♦ The entire SalesRep table.
♦ Those rows from the Policy table that include sales relationships
involving the sales rep subscribed to the data.
♦ Those rows from the Customer table listing customers that deal with the
sales rep subscribed to the data.

New problems The many-to-many relationship between customers and sales representatives
introduces new challenges in maintaining a proper sharing of information:
♦ We have a table (in this case the Customer table) that has no reference to
the sales representative value that is used in the subscriptions to partition
the data.
Again, this problem is addressed by using a subquery in the publication.
♦ Each row in the Customer table may be related to many rows in the
SalesRep table, and shared with many sales representatives databases.

340
Chapter 15 SQL Remote Design for Adaptive Server Anywhere

Put another way, the rows of the Contact table in "Partitioning tables
that do not contain the subscription expression" on page 330 were
partitioned into disjoint sets by the publication. In the present example
there are overlapping subscriptions.
To meet the replication goals we again need one publication and a set of
subscriptions. In this case, we use two triggers to handle the transfer of
customers from one sales representative to another.

The publication
A single publication provides the basis for the data sharing:
CREATE PUBLICATION SalesRepData (
TABLE SalesRep,
TABLE Policy SUBSCRIBE BY rep_key,
TABLE Customer SUBSCRIBE BY (
SELECT rep_key FROM Policy
WHERE Policy.cust_key =
Customer.cust_key
),
);
The subscription statements are exactly as in the previous example.
How the The publication includes part or all of each of the three tables. To understand
publication works how the publication works, it helps to look at each article in turn:
♦ SalesRep table There are no qualifiers to this article, so the entire
SalesRep table is included in the publication.

TABLE SalesRep,

♦ Policy table This article uses a subscription expression to specify a
column used to partition the data among the sales reps:

TABLE Policy
SUBSCRIBE BY rep_key,

The subscription expression ensures that each sales rep receives only
those rows of the table for which the value of the rep_key column
matches the value provided in the subscription.
The Policy table partitioning is disjoint: there are no rows that are
shared with more than one subscriber.
♦ Customer table A subscription expression with a subquery is
used to define the partition. The article is defined as follows:

341
Sharing rows among several subscriptions


TABLE Customer SUBSCRIBE BY (
SELECT rep_key
FROM Policy
WHERE Policy.cust_key =
Customer.cust_key
),

The Customer partitioning is non-disjoint: some rows are shared with
more than one subscriber.

Multiple-valued The subquery in the Customer article returns a single column (rep_key) in
subqueries in its result set, but may return multiple rows, corresponding to all those sales
publications representatives that deal with the particular customer. When a subscription
expression has multiple values, the row is replicated to all subscribers whose
subscription matches any of the values. It is this ability to have multiple-
valued subscription expressions that allows non-disjoint partitionings of a
table.

Territory realignment with a many-to-many relationship


The problem of territory realignment (reassigning rows among subscribers)
requires special attention, just as in the section "Territory realignment in the
Contact example" on page 333.
You need to write triggers to maintain proper data throughout the installation
when territory realignment (reassignment of rows among subscribers) is
allowed.
How customers are In this example, we require that a customer transfer be achieved by deleting
transferred and inserting rows in the Policy table.
To cancel a sales relationship between a customer and a sales representative,
a row in the Policy table is deleted. In this case, the Policy table change is
properly replicated to the sales representative, and the row no longer appears
in their database. However, no change has been made to the Customer table,
and so no changes to the Customer table are replicated to the subscriber.
In the absence of triggers, this would leave the subscriber with incorrect data
in their Customer table. The same kind of problem arises when a new row is
added to the Policy table.
Using Triggers to The solution is to write triggers that are fired by changes to the Policy table,
solve the problem which include a special syntax of the UPDATE statement. The special
UPDATE statement makes no changes to the database tables, but does make
an entry in the transaction log that SQL Remote uses to maintain data in
subscriber databases.

342
Chapter 15 SQL Remote Design for Adaptive Server Anywhere

A BEFORE Here is a trigger that tracks INSERTS into the Policy table, and ensures that
INSERT trigger remote databases contain the proper data.
CREATE TRIGGER InsPolicy
BEFORE INSERT ON Policy
REFERENCING NEW AS NewRow
FOR EACH ROW
BEGIN
UPDATE Customer
PUBLICATION SalesRepData
SUBSCRIBE BY (
SELECT rep_key
FROM Policy
WHERE cust_key = NewRow.cust_key
UNION ALL
SELECT NewRow.rep_key
)
WHERE cust_key = NewRow.cust_key;
END;

A BEFORE Here is a corresponding trigger that tracks DELETES from the Policy table:
DELETE trigger CREATE TRIGGER DelPolicy
BEFORE DELETE ON Policy
REFERENCING OLD AS OldRow
FOR EACH ROW
BEGIN
UPDATE Customer
PUBLICATION SalesRepData
SUBSCRIBE BY (
SELECT rep_key
FROM Policy
WHERE cust_key = OldRow.cust_key
AND Policy_key <> OldRow.Policy_key
)
WHERE cust_key = OldRow.cust_key;
END;
Some of the features of the trigger are the same as in the previous section.
The major new features are that the INSERT trigger contains a subquery, and
that this subquery can be multi-valued.
Multiple-valued The subquery in the BEFORE INSERT trigger is a UNION expression, and
subqueries can be multi-valued:

SELECT rep_key
FROM Policy
WHERE cust_key = NewRow.cust_key
UNION ALL
SELECT NewRow.rep_key

343
Sharing rows among several subscriptions


♦ The second part of the UNION is the rep_key value for the new sales
representative dealing with the customer, taken from the INSERT
statement.
♦ The first part of the UNION is the set of existing sales representatives
dealing with the customer, taken from the Policy table.
This illustrates the point that the result set of the subscription query must
be all those sales representatives receiving the row, not just the new
sales representatives.
The subquery in the BEFORE DELETE trigger is multi-valued:

SELECT rep_key
FROM Policy
WHERE cust_key = OldRow.cust_key
AND rep_key <> OldRow.rep_key

♦ The subquery takes rep_key values from the Policy table. The values
include the primary-key values of all those sales reps who deal with the
customer being transferred (WHERE cust_key = OldRow.cust_key),
with the exception of the one being deleted (AND rep_key <>
OldRow.rep_key).
This again emphasizes that the result set of the subscription query must
be all those values matched by sales representatives receiving the row
following the DELETE.

Notes ♦ Data in the Customer table is not identified with an individual


subscriber (by a primary key value, for example) and is shared among
more than one subscriber. This allows the possibility of the data being
updated in more than one remote site between replication messages,
which could lead to replication conflicts. You can address this issue
either by permissions (allowing only certain users the right to update the
Customer table, for example) or by adding RESOLVE UPDATE
triggers to the database to handle the conflicts programmatically.
♦ UPDATES on the Policy table have not been described here. They
should either be prevented, or a BEFORE UPDATE trigger is required
that combines features of the BEFORE INSERT and BEFORE DELETE
triggers shown in the example.

344
Chapter 15 SQL Remote Design for Adaptive Server Anywhere

Using the Subscribe_by_remote option with many-to-many


relationships
When the Subscribe_by_remote option is ON, operations from remote
databases on rows with a subscribe by value of NULL or an empty string
will assume the remote user is subscribed to the row. By default, the
Subscribe_by_remote option is set to ON. In most cases, this setting is the
desired setting.
The Subscribe_by_remote option solves a problem that otherwise would
arise with some publications, including the Policy example. This section
describes the problem, and how the option automatically avoids it.
The publication uses a subquery for the Customer table subscription
expression, because each Customer may belong to several Sales Reps:
CREATE PUBLICATION SalesRepData (
TABLE SalesRep,
TABLE Policy SUBSCRIBE BY rep_key,
TABLE Customer SUBSCRIBE BY (
SELECT rep_key FROM Policy
WHERE Policy.cust_key =
Customer.cust_key
),
);
Marc Dill is a Sales Rep who has just arranged a policy with a new customer.
He inserts a new Customer row and also inserts a row in the Policy table to
assign the new Customer to himself.

Customer Policy SalesRep

cust1010 pol2345 195

cust_name cust1010 Marc Dill

195

As the INSERT of the Customer row is carried out by the Message Agent at
the consolidated database, Adaptive Server Anywhere records the
subscription value in the transaction log, at the time of the INSERT.
Later, when the Message Agent scans the log, it builds a list of subscribers
from the subscription expression, and Marc Dill is not on the list, as the row
in the Policy table assigning the customer to him has not yet been applied. If
Subscribe_by_remote were set to OFF, the result would be that the new
Customer is sent back to Marc Dill as a DELETE operation.

345
Sharing rows among several subscriptions

As long as Subscribe_by_remote is set to ON, the Message Agent assumes


the row belongs to the Sales Rep that inserted it, the INSERT is not
replicated back to Marc Dill, and the replication system is intact.
If Subscribe_by_remote is set to OFF, you must ensure that the Policy row is
inserted before the Customer row, with the referential integrity violation
avoided by postponing checking to the end of the transaction.

346
Chapter 15 SQL Remote Design for Adaptive Server Anywhere

Managing conflicts
An UPDATE conflict occurs when the following sequence of events takes
place:
1 User 1 updates a row at remote site 1.
2 User 2 updates the same row at remote site 2.
3 The update from User 1 is replicated to the consolidated database.
4 The update from User 2 is replicated to the consolidated database.
When the SQL Remote Message Agent replicates UPDATE statements, it
does so as a separate UPDATE for each row. Also, the message contains the
old row values for comparison. When the update from user 2 arrives at the
consolidated database, the values in the row are not those recorded in the
message.

347
Managing conflicts

uploaded new
choose one
and old row
uploaded
values from one
row
remote table

Was this row


inserted or updated in
the remote
database?

update another row


insert
compare
old values
with matching conflict
consolidated
row
insert old values using
old_row_cursor script
values match

insert new values using


insert new row update row new_row_cursor script
using using
upload_rows upload_rows
script script execute
resolve_conflict
script

any more
uploaded rows?

no more rows

finished
inserts and updates
from this table

Default conflict By default, the UPDATE still proceeds, so that the User 2 update (the last to
resolution reach the consolidated database) becomes the value in the consolidated
database, and is replicated to all other databases subscribed to that row.
In general, the default method of conflict resolution is that the most recent
operation (in this case that from User 2) succeeds, and no report is made of
the conflict. The update from User 1 is lost. SQL Remote also allows custom
conflict resolution, using a trigger to resolve conflicts in a way that makes
sense for the data being changed.

348
Chapter 15 SQL Remote Design for Adaptive Server Anywhere

Conflict resolution does not apply to primary key updates


UPDATE conflicts do not apply to primary key updates. You should not
update primary keys in a SQL Remote installation. Primary key conflicts
must be excluded from the installation by proper design.

This section describes how you can build conflict resolution into your
SQL Remote installation at the consolidated database.

How SQL Remote handles conflicts


When a conflict is SQL Remote replication messages include UPDATE statements as a set of
detected single row updates, each with a VERIFY clause that includes values prior to
updating.
An UPDATE conflict is detected by the database server as a failure of the
VERIFY clause values to match the rows in the database.
Conflicts are detected and resolved by the Message Agent, but only at a
consolidated database. When an UPDATE conflict is detected in a message
from a remote database, the Message Agent causes the database server to
take two actions:
1 Any conflict resolution (RESOLVE UPDATE) triggers are fired.
2 The UPDATE is applied.
UPDATE statements are applied even if the VERIFY clause values do not
match, whether or not there is a RESOLVE UPDATE trigger.
Conflict resolution can take several forms. For example:
♦ In some applications, resolution could mean reporting the conflict into a
table.
♦ You may wish to keep updates made at the consolidated database in
preference to those made at remote sites.
♦ Conflict resolution can be more sophisticated, for example in resolving
inventory numbers in the face of goods deliveries and orders.
$ The method of conflict resolution is different at an Adaptive Server
Enterprise consolidated database. For more information, see "How
SQL Remote handles conflicts" on page 396.

349
Managing conflicts

Implementing conflict resolution


This section describes what you need to do to implement custom conflict
resolution in SQL Remote for Adaptive Server Anywhere. The concepts are
the same in SQL Remote for Adaptive Server Enterprise, but the
implementation is different.
SQL Remote allows you to define conflict resolution triggers to handle
UPDATE conflicts. Conflict resolution triggers are fired only at a
consolidated database, when messages are applied by a remote user. When
an UPDATE conflict is detected at a consolidated database, the following
sequence of events takes place.
1 Any conflict resolution triggers defined for the operation are fired.
2 The UPDATE takes place.
3 Any actions of the trigger, as well as the UPDATE, are replicated to all
remote databases, including the sender of the message that triggered the
conflict.
In general, SQL Remote for Adaptive Server Anywhere does not
replicate the actions of triggers: the trigger is assumed to be present at
the remote database. Conflict resolution triggers are fired only at
consolidated databases, and so their actions are replicated to remote
databases.
4 At remote databases, no RESOLVE UPDATE triggers are fired when a
message from a consolidated database contains an UPDATE conflict.
5 The UPDATE is carried out at the remote databases.
At the end of the process, the data is consistent throughout the setup.
UPDATE conflicts cannot happen where data is shared for reading, but each
row (as identified by its primary key) is updated at only one site. They only
occur when data is being updated at more than one site.

Using conflict resolution triggers


This section describes how to use RESOLVE UPDATE, or conflict
resolution triggers.
UPDATE Conflict resolution triggers are fired by the failure of values in the VERIFY
statements with a clause of an UPDATE statement to match the values in the database before
VERIFY clause the update. An UPDATE statement with a VERIFY clause takes the
following form:
UPDATE table-list
SET column-name = expression, ...

350
Chapter 15 SQL Remote Design for Adaptive Server Anywhere

[ FROM table-list ]
[ VERIFY (column-name, ...)
VALUES ( expression, ...) ]
[ WHERE search-condition ]
The VERIFY clause compares the values of specified columns to a set of
expected values, which are the values that were present in the publisher
database when the UPDATE statement was applied there.
The verify clause is useful only for single-row updates. However, multi-row
update statements entered at a database are replicated as a set of single-row
updates by the Message Agent, so this imposes no constraints on client
applications.
Conflict resolution The syntax for a RESOLVE UPDATE trigger is as follows:
trigger syntax
CREATE TRIGGER trigger-name
RESOLVE UPDATE
OF column-name ON table-name
[ REFERENCING [ OLD AS old_val ]
[ NEW AS new_val ]
[ REMOTE AS remote_val ] ]
FOR EACH ROW
BEGIN
...
END
RESOLVE UPDATE triggers fire before each row is updated. The
REFERENCING clause allows access to the values in the row of the table to
be updated (OLD), to the values the row is to be updated to (NEW) and to
the rows that should be present according to the VERIFY clause (REMOTE).
Only columns present in the VERIFY clause can be referenced in the
REMOTE AS clause; other columns produce a "column not found" error.
Using the The database option VERIFY_ALL_COLUMNS is OFF by default. If it is
VERIFY_ALL_ set to ON, all columns are verified on replicated updates, and a RESOLVE
COLUMNS option UPDATE trigger is fired whenever any column is different. If it is set to
OFF, only those columns that are updated are checked.
Setting this option to ON makes messages bigger, because more information
is sent for each UPDATE.
If this option is set at the consolidated database before remote databases are
extracted, it will be set at the remote databases also.
You can set the VERIFY_ALL_COLUMNS option either for the PUBLIC
group or just for the user contained in the Message Agent connection string.
Using the The CURRENT REMOTE USER special constant holds the user ID of the
CURRENT remote user sending the message. This can be used in RESOLVE UPDATE
REMOTE USER triggers that place reports of conflicts into a table, to identify the user
special constant producing a conflict.

351
Managing conflicts

Conflict resolution examples


This section describes some ways of using RESOLVE UPDATE triggers to
handle conflicts.

Resolving date conflicts


Suppose a table in a contact management system has a column holding the
most recent contact with each customer.
One representative talks with a customer on a Friday, but does not upload his
changes to the consolidated database until the next Monday. Meanwhile, a
second representative meets the customer on the Saturday, and updates the
changes that evening.
There is no conflict when the Saturday UPDATE is replicated to the
consolidated database, but when the Monday UPDATE arrives it finds the
row already changed.
By default, the Monday UPDATE would proceed, leaving the column with
the incorrect information that the most recent contact occurred on Friday.
Update conflicts on this column should be resolved by inserting the most
recent date in the row.
Implementing the The following RESOLVE UPDATE trigger chooses the most recent of the
solution two new values and enters it in the database.
CREATE TRIGGER contact_date RESOLVE UPDATE
ON contact
REFERENCING OLD AS old_name
NEW AS new_name
FOR EACH ROW
BEGIN
IF new_name.contact_date <
old_name.contact_date THEN
SET new_name.contact_date
= old_name.contact_date
END IF
END
If the value being updated is later than the value that would replace it, the
new value is reset to leave the entry unchanged.

Resolving inventory conflicts


Consider a warehouse system for a manufacturer of sporting goods. There is
a table of product information, with a quantity column holding the number
of each product left in stock. An update to this column will typically deplete
the quantity in stock or, if a new shipment is brought in, add to it.
352
Chapter 15 SQL Remote Design for Adaptive Server Anywhere

A sales representative at a remote database enters an order, depleting the


stock of small tank top tee shirts by five, from 28 to 23, and enters this in on
her database. Meanwhile, before this update is replicated to the consolidated
database, a new shipment of tee shirts comes in, and the warehouse enters the
shipment, adding 40 to the quantity column to make it 68.

28 > 68

Updates
made at
remote
28 > 23 28 > 68
databases

The warehouse entry gets added to the database: the quantity column now
shows there are 68 small tank-top tee shirts in stock. When the update from
the sales representative arrives, it causes a conflict–Adaptive Server
Anywhere detects that the update is from 28 to 23, but that the current value
of the column is 68.
By default, the most recent UPDATE succeeds, and the inventory level is set
to the incorrect value of 23.

Default
conflict
resolution: 68 > 23
wrong result

28 > 23 28 > 68

In this case the conflict should be resolved by summing the changes to the
inventory column to produce the final result, so that a final value of 63 is
placed into the database.

353
Managing conflicts

Conflict
resolution
trigger:
correct 68 > 63
result

28 > 23 28 > 68

Implementing the A suitable RESOLVE UPDATE trigger for this situation would add the
solution increments from the two updates. For example:
CREATE TRIGGER resolve_quantity
RESOLVE UPDATE OF quantity
ON "DBA".product
REFERENCING OLD AS old_name
NEW AS new_name
REMOTE AS remote_name
FOR EACH ROW
BEGIN
SET new_name.quantity = new_name.quantity
+ old_name.quantity
- remote_name.quantity
END
This trigger adds the difference between the old value in the consolidated
database (68) and the old value in the remote database when the original
UPDATE was executed (28) to the new value being sent, before the
UPDATE is implemented. Thus, new_val.quantity becomes 63 (= 23 + 68 -
28), and this value is entered into the quantity column.
Consistency is maintained at the remote database as follows:
1 The original remote UPDATE changed the value from 28 to 23.
2 The warehouse’s entry is replicated to the remote database, but fails as
the old value is not what was expected.
3 The changes made by the RESOLVE UPDATE trigger are replicated to
the remote database.

354
Chapter 15 SQL Remote Design for Adaptive Server Anywhere

Reporting conflicts
In some cases, you may not want to alter the default way in which
SQL Remote resolves conflicts; you may just want to report the conflicts by
storing them in a table. In this way, you can look at the conflict table to see
what, if any, conflicts have occurred, and if necessary take action to resolve
the conflicts.

Designing to avoid referential integrity errors


The tables in a relational database are related through foreign key references.
The referential integrity constraints applied as a consequence of these
references ensure that the database remains consistent. If you wish to
replicate only a part of a database, there are potential problems with the
referential integrity of the replicated database.
By paying attention to referential integrity issues while designing
publications you can avoid these problems. This section describes some of
the more common integrity problems and suggests ways to avoid them.
Unreplicated The sales publication described in "Publishing a set of tables" on page 319
referenced table includes the sales_order table:
errors CREATE PUBLICATION pub_sales (
TABLE customer,
TABLE sales_order,
TABLE sales_order_items,
TABLE product
)
The sales_order table has a foreign key to the employee table. The id of the
sales rep is a foreign key in the sales_order table referencing the primary
key of the employee table. However, the employee table is not included in
the publication.
If the publication is created in this manner, new sales orders would fail to
replicate unless the remote database has the foreign key reference removed
from the sales_order table.
If you use the extraction utility to create the remote databases, the foreign
key reference is automatically excluded from the remote database, and this
problem is avoided. However, there is no constraint in the database to
prevent an invalid value from being inserted into the sales_rep_id column of
the sales_order table, and if this happens the INSERT will fail at the
consolidated database. To avoid this problem, you can include the employee
table (or at least its primary key) in the publication.

355
Managing conflicts

Designing triggers to avoid errors


Actions performed by triggers are not replicated: triggers that exist at one
database in a SQL Remote setup are assumed by the replication procedure to
exist at other databases in the setup. When an action that fires a trigger at the
consolidated database is replicated at the replicate site, the trigger is
automatically fired. By default, the database extraction utility extracts the
trigger definitions, so that they are in place at the remote database also.
If a publication includes only a subset of a database, a trigger at the
consolidated database may refer to tables or rows that are present at the
consolidated database, but not at the remote databases. You can design your
triggers to avoid such errors by making actions of the trigger conditional
using an IF statement. The following list suggests some ways in which
triggers can be designed to work on consolidated and remote databases.
♦ Have actions of the trigger be conditional on the value of CURRENT
PUBLISHER. In this case, the trigger would not execute certain actions
at the remote database.
♦ Have actions of the trigger be conditional on the object_id function not
returning NULL. The object_id function takes a table or other object as
argument, and returns the ID number of that object or NULL if the
object does not exist.
♦ Have actions of the trigger be conditional on a SELECT statement
which determines if rows exist.
The RESOLVE UPDATE trigger is a special trigger type for the resolution
of UPDATE conflicts, and is discussed in the section "Conflict resolution
examples" on page 352. The actions of RESOLVE UPDATE triggers are
replicated to remote databases, including the database that caused the
conflict.

356
Chapter 15 SQL Remote Design for Adaptive Server Anywhere

Ensuring unique primary keys


Primary-key values must be unique. When all users are connected to the
same database, there is no problem keeping unique values. If a user tries to
re-use a value, the INSERT statement fails.
The situation is different in a replication system because users are connected
to many databases. A potential problem arises when two users, connected to
different databases, insert a row using the same primary-key value. Each of
their statements succeeds because the value is unique in each database.
However, problems arise in a replication system when two users, connected
to separate databases, INSERT a row using the same primary-key value. The
second INSERT to reach a given database in the replication system fails. As
SQL Remote is a replication system for occasionally connected users, there
can be no locking mechanism across all databases in the installation. It is
necessary to design your SQL Remote installation so that primary-key
duplication errors do not occur.
For primary-key errors to be designed out of SQL Remote installations, the
primary keys of tables that may be modified at more than one site must be
guaranteed unique. There are several ways of achieving this goal. This
chapter describes two general, economical, and reliable methods.
1 Using the default global autoincrement feature of Adaptive Server
Anywhere.
2 Using the primary-key pools to maintain a list of unused, unique
primary-key values at each site.
You can use these techniques either separately or together to avoid duplicate
values.

Using the default global autoincrement feature


In Adaptive Server Anywhere, you can set the default column value to be
GLOBAL AUTOINCREMENT. You can use this default for any column in
which you want to maintain unique values, but it is particularly useful for
primary keys.

357
Ensuring unique primary keys

When you specify this default, the domain of values for that column is
partitioned. The size of each partition can be specified in parentheses
immediately following the AUTOINCREMENT key word. This value may
be any positive integer, although the partition size is generally chosen so that
the supply of numbers within any one partition will rarely, if ever, be
exhausted. If the column is of type BIGINT or UNSIGNED BIGINT, the
default partition size is 2**32 = 4294967296; for columns of other types the
default partition size is 2**16 = 65536.
$ For more information on GLOBAL AUTOINCREMENT, see
"CREATE TABLE statement" on page 453 of the book ASA Reference.
Value depends on To make use of this default, the value of the public option
Global_database_i Global_database_id in each database must be set to a unique, positive
d integer. This value uniquely identifies the database and indicates from which
partition default values are to be assigned. The range of allowed values is
n p + 1 to (n + 1) p, where n is the value of the public option
Global_database_id and p is the partition size. For example, if the partition
size is 1000 and Global_database_id is set to 3, then the range is from 3001
to 4000.
If the previous value is less than (n + 1) p, the next default value will be one
greater than the previous largest value in column. If the column contains no
values, the first default value is n p + 1.
If the public option Global_database_id is set to zero, a null value is
inserted into the column. Should null values not be permitted, the attempt to
insert the row causes an error. This situation arises, for example, if the
column is contained in the table’s primary key. The public option
Global_database_id is set to zero by default.
Null default values are also generated when the supply of values within the
partition has been exhausted. In this case, a new value of
Global_database_id should be assigned to the database to allow default
values to be chosen from another partition. Attempting to insert the null
value causes an error if the column does not permit nulls. To detect that the
supply of unused values is low and handle this condition, create an event of
type GlobalAutoincrement.
Should the values in a particular partition become exhausted, you can assign
a new database id to that database. You can assign new database id numbers
in any convenient manner. However, one possible technique is to maintain a
pool of unused database id values. This pool is maintained in the same
manner as a pool of primary keys.
You can set an event handler to automatically notify the database
administrator (or carry out some other action) when the partition is nearly
exhausted. For more information, see "Defining trigger conditions for
events" on page 487 of the book ASA User’s Guide.

358
Chapter 15 SQL Remote Design for Adaptive Server Anywhere

$ For more information, see "GLOBAL_DATABASE_ID option" on


page 176 of the book ASA Reference.
$ For further information on pools, see "Using primary-key pools" on
page 360.

Setting the Global_database_id value


Each database in the installation must have a different value of
GLOBAL_DATABASE_ID to ensure unique primary key values, and these
values must be spaced widely enough apart that the pool available to each
database is large enough for your application.
If you use the extraction utility to create your remote databases, you can
write a stored procedure to automate the task. If you create a stored
procedure named sp_hook_dbxtract_begin, it is called automatically by the
extraction utility. Before the procedure is called, the extraction utility creates
a temporary table named #hook_dict, with the following contents:

name value
extracted_db_global_id user ID being extracted

If you write your sp_hook_dbxtract_begin procedure to modify the value


column of the row, that value is used as the GLOBAL_DATABASE_ID
option of the extracted database, and marks the beginning of the range of
primary key values for GLOBAL DEFAULT AUTOINCREMENT values.
Example Consider extracting a database for remote user user2 with a user_id of 101.
If you do not define an sp_hook_dbxtract_begin procedure, the extracted
database will have Global_database_id set to 101.
If you define a sp_hook_dbxtract_begin procedure, but it does not modify
any rows in the #hook_dict then the option will still be set to 101.
If you set up the database as follows:
set option "PUBLIC"."Global_database_id" = ’1’;
create table extract_id ( next_id integer not null) ;
insert into extract_id values( 1 );

359
Ensuring unique primary keys

create procedure sp_hook_dbxtract_begin


as
declare @next_id integer
update extract_id set next_id = next_id + 1000
select @next_id = (next_id )
from extract_id
commit
update #hook_dict
set value = @next_id
where name = ’extracted_db_global_id’
Then each extracted or re-extracted database will get a different
Global_database_id. The first starts at 1001, the next at 2001, and so on.
To assist in debugging procedure hooks, dbxtract outputs the following when
it is set to operate in verbose mode:
♦ the procedure hooks found
♦ the contents of #hook_dict before the procedure hook is called
♦ the contents of #hook_dict after the procedure hook is called.

Using primary-key pools


The primary-key pool is a table that holds a set of primary-key values for
each database in the SQL Remote installation. Each remote user receives
their own set of primary-key values. When a remote user inserts a new row
into a table, they use a stored procedure to select a valid primary key from
the pool. The pool is maintained by periodically running a procedure at the
consolidated database that replenishes the supply.
The method is described using a simple example database consisting of sales
representatives and their customers. The tables are much simpler than you
would use in a real database; this allows us to focus just on those issues
important for replication.

The primary-key pool table


The pool of primary keys is held in a separate table. The following CREATE
TABLE statement creates a primary-key pool table:
CREATE TABLE KeyPool (
table_name VARCHAR(40) NOT NULL,
value INTEGER NOT NULL,
location CHAR(12) NOT NULL,
PRIMARY KEY (table_name, value),
);

360
Chapter 15 SQL Remote Design for Adaptive Server Anywhere

The columns of this table have the following meanings:

Column Description
table_name Holds the names of tables for which primary-key pools must be
maintained. In our simple example, if new sales representatives
were to be added only at the consolidated database, only the
Customer table needs a primary-key pool and this column is
redundant. It is included to show a general solution.
value Holds a list of primary-key values. Each value is unique for each
table listed in table_name.
location An identifier for the recipient. In some setups, this could be the
same as the rep_key value of the SalesRep table. In other setups,
there will be users other than sales representatives and the two
identifiers should be distinct.

For performance reasons, you may wish to create an index on the table:
CREATE INDEX KeyPoolLocation
ON KeyPool (table_name, location, value);

Replicating the primary-key pool


You can either incorporate the key pool into an existing publication, or share
it as a separate publication. In this example, we create a separate publication
for the primary-key pool.

v To replicate the primary-key pool (SQL):


1 Create a publication for the primary-key pool data.
CREATE PUBLICATION KeyPoolData (
TABLE KeyPool SUBSCRIBE BY location
);
2 Create subscriptions for each remote database to the KeyPoolData
publication.
CREATE SUBSCRIPTION
TO KeyPoolData( ’user1’ )
FOR user1;
CREATE SUBSCRIPTION
TO KeyPoolData( ’user2’ )
FOR user2;

The subscription argument is the location identifier.

361
Ensuring unique primary keys

In some circumstances it makes sense to add the KeyPool table to an existing


publication and use the same argument to subscribe to each publication. Here
we keep the location and rep_key values distinct to provide a more general
solution.
$ See also
♦ "CREATE PUBLICATION statement" on page 579
♦ "CREATE SUBSCRIPTION statement" on page 583

Filling and replenishing the key pool


Every time a user adds a new customer, their pool of available primary keys
is depleted by one. The primary-key pool table needs to be periodically
replenished at the consolidated database using a procedure such as the
following:
CREATE PROCEDURE ReplenishPool()
BEGIN
FOR EachTable AS TableCursor
CURSOR FOR
SELECT table_name
AS CurrTable, max(value) as MaxValue
FROM KeyPool
GROUP BY table_name
DO
FOR EachRep AS RepCursor
CURSOR FOR
SELECT location
AS CurrRep, count(*) as NumValues
FROM KeyPool
WHERE table_name = CurrTable
GROUP BY location
DO
// make sure there are 100 values.
// Fit the top-up value to your
// requirements
WHILE NumValues < 100 LOOP
SET MaxValue = MaxValue + 1;
SET NumValues = NumValues + 1;
INSERT INTO KeyPool
(table_name, location, value)
VALUES
(CurrTable, CurrRep, MaxValue);
END LOOP;
END FOR;
END FOR;
END;

362
Chapter 15 SQL Remote Design for Adaptive Server Anywhere

This procedure fills the pool for each user up to 100 values. The value you
need depends on how often users are inserting rows into the tables in the
database.
The ReplenishPool procedure must be run periodically at the consolidated
database to refill the pool of primary-key values in the KeyPool table.
The ReplenishPool procedure requires at least one primary key value to
exist for each subscriber, so that it can find the maximum value and add one
to generate the next set. To initially fill the pool you can insert a single value
for each user, and then call ReplenishPool to fill up the rest. The following
example illustrates this for three remote users and a single consolidated user
named Office:
INSERT INTO KeyPool VALUES( ’Customer’, 40, ’user1’ );
INSERT INTO KeyPool VALUES( ’Customer’, 41, ’user2’ );
INSERT INTO KeyPool VALUES( ’Customer’, 42, ’user3’ );
INSERT INTO KeyPool VALUES( ’Customer’, 43, ’Office’);
CALL ReplenishPool();

Cannot use a trigger to replenish the key pool


You cannot use a trigger to replenish the key pool, as trigger actions are
not replicated.

Adding new customers


When a sales representative wants to add a new customer to the Customer
table, the primary key value to be inserted is obtained using a stored
procedure. This example shows a stored procedure to supply the primary key
value, and also illustrates a stored procedure to carry out the INSERT.
The procedures takes advantage of the fact that the Sales Rep identifier is the
CURRENT PUBLISHER of the remote database.
♦ NewKey procedure The NewKey procedure supplies an integer value
from the key pool and deletes the value from the pool.
CREATE PROCEDURE NewKey(
IN @table_name VARCHAR(40),
OUT @value INTEGER )
BEGIN
DECLARE NumValues INTEGER;

SELECT count(*), min(value)


INTO NumValues, @value
FROM KeyPool
WHERE table_name = @table_name
AND location = CURRENT PUBLISHER;

363
Ensuring unique primary keys

IF NumValues > 1 THEN


DELETE FROM KeyPool
WHERE table_name = @table_name
AND value = @value;
ELSE
// Never take the last value, because
// ReplenishPool will not work.
// The key pool should be kept large enough
// that this never happens.
SET @value = NULL;
END IF;
END;
♦ NewCustomer procedure The NewCustomer procedure inserts a
new customer into the table, using the value obtained by NewKey to
construct the primary key.
CREATE PROCEDURE NewCustomer(
IN customer_name CHAR( 40 ) )
BEGIN
DECLARE new_cust_key INTEGER ;
CALL NewKey( ’Customer’, new_cust_key );
INSERT
INTO Customer (
cust_key,
name,
location
)
VALUES (
’Customer ’ ||
CONVERT (CHAR(3), new_cust_key),
customer_name,
CURRENT PUBLISHER
);
);
END
You may want to enhance this procedure by testing the new_cust_key
value obtained from NewKey to check that it is not NULL, and
preventing the insert if it is NULL.

Primary-key pool summary


The primary-key pool technique requires the following components:
♦ Key pool table A table to hold valid primary-key values for each
database in the installation.
♦ Replenishment procedure A stored procedure keeps the key pool
table filled.

364
Chapter 15 SQL Remote Design for Adaptive Server Anywhere

♦ Sharing of key pools Each database in the installation must subscribe


to its own set of valid values from the key pool table.
♦ Data entry procedures New rows are entered using a stored
procedure that picks the next valid primary key value from the pool and
delete that value from the key pool.

365
Creating subscriptions

Creating subscriptions
To subscribe to a publication, each subscriber must be granted REMOTE
permissions and a subscription must also be created for that user. The details
of the subscription are different depending on whether or not the publication
uses a subscription expression.
Working with
v To create and manage subscriptions in Sybase Central
subscriptions in
Sybase Central 1 Open the Publications folder (located within the SQL Remote folder).
2 Right-click a publication and choose Properties from the popup menu.
3 Click the Subscriptions tab and configure the appropriate settings:
♦ To subscribe a remote user to the publication, click Subscribe For
and enter the desired values in the resulting dialog.
♦ To unsubscribe a remote user, select the user in the list and click
Unsubscribe.
♦ To manually start, stop, or synchronize subscriptions, click either
Start Now, Stop Now, or Synchronize Now. The subscriptions are
affected as soon as you click the button. Subsequently clicking
Cancel on the property sheet does not cancel your
start/stop/synchronize action.

Tips
You can also manage subscriptions on the SQL Remote tab of a remote
user’s property sheet. Remote users appear in two locations: in the Users
& Groups folder and in the Remote Users folder (located within the
SQL Remote folder).
For a description of all property sheets in Sybase Central, see "Property
Sheet Descriptions" on page 1035 of the book ASA User’s Guide.

Subscriptions with To subscribe a user to a publication, if that publication has no subscription


no subscription expression, you need the following information:
expression
♦ User ID The user who is being subscribed to the publication. This user
must have been granted remote permissions.
♦ Publication name The name of the publication to which the user is
being subscribed.
The following statement creates a subscription for a user ID SamS to the
pub_orders_samuel_singer publication, which was created using a
WHERE clause:

366
Chapter 15 SQL Remote Design for Adaptive Server Anywhere

CREATE SUBSCRIPTION
TO pub_orders_samuel_singer
FOR SamS

Subscriptions with To subscribe a user to a publication, if that publication does have a


a subscription subscription expression, you need the following information:
expression
♦ User ID The user who is being subscribed to the publication. This user
must have been granted remote permissions.
♦ Publication name The name of the publication to which the user is
being subscribed.
♦ Subscription value The value that is to be tested against the
subscription expression of the publication. For example, if a publication
has the name of a column containing an employee ID as a subscription
expression, the value of the employee ID of the subscribing user must be
provided in the subscription. The subscription value is always a string.
The following statement creates a subscription for Samuel Singer (user ID
SamS, employee ID 856) to the pub_orders publication, defined with a
subscription expression sales_rep, requesting the rows for Samuel Singer’s
own sales:
CREATE SUBSCRIPTION
TO pub_orders ( ’856’ )
FOR SamS

Starting a In order to receive and apply updates properly, each subscriber needs to have
subscription an initial copy of the data. The synchronization process is discussed in
"Synchronizing databases" on page 417.
$ See also
♦ "CREATE SUBSCRIPTION statement" on page 583
♦ "Property Sheet Descriptions" on page 1035 of the book ASA User’s
Guide

367
Creating subscriptions

368
C H A P T E R 1 6

SQL Remote Design for Adaptive Server


Enterprise

About this chapter This chapter describes how to design a SQL Remote installation when the
consolidated database is at an Adaptive Server Enterprise server.

Similar material for Adaptive Server Anywhere


Many of the principles of publication design are the same for Adaptive
Server Anywhere and Adaptive Server Enterprise, but there are
differences in commands and capabilities. There is a large overlap
between this chapter and the corresponding chapter for Adaptive Server
Anywhere users, "SQL Remote Design for Adaptive Server Anywhere"
on page 315.

Contents
Topic Page
Design overview 370
Creating publications 371
Publication design for Adaptive Server Enterprise 376
Partitioning tables that do not contain the subscription column 378
Sharing rows among several subscriptions 386
Managing conflicts 394
Ensuring unique primary keys 405
Creating subscriptions 411

369
Design overview

Design overview
Designing a SQL Remote installation includes the following tasks:
♦ Designing publications The publications determine what information
is shared among which databases.
♦ Designing subscriptions The subscriptions determine what
information each user receives.
♦ Implementing the design Creating publications and subscriptions for
all users in the system.

All administration is Like all SQL Remote administrative tasks, design is carried out by a database
at the consolidated administrator or system administrator at the consolidated database. The
database Sybase System Administrator should perform all SQL Remote configuration
tasks.
$ For more information about the Adaptive Server Enterprise
environment, see your Adaptive Server Enterprise documentation.

370
Chapter 16 SQL Remote Design for Adaptive Server Enterprise

Creating publications
In this section This section describes how to create simple publications consisting of whole
tables, or of column-wise subsets of tables.
$ Simple publications are also discussed in the chapter "A Tutorial for
Adaptive Server Enterprise Users" on page 269.

Creating publications for Adaptive Server Enterprise using Sybase


Central
In Sybase Central, you can add a publication to a database from within the
SQL Remote folder. The SQL Remote folder is displayed inside a database
container.

v To create a publication from Sybase Central:


1 Click the Publications folder, which is inside the SQL Remote folder.
2 Double-click Add Publication. The Publication Wizard is displayed.
3 Follow the instructions in the Wizard.
$ For more information, see the Sybase Central online Help.
With Sybase Central, you do not need to know the SQL syntax in order to
create publications. The remainder of this section discusses different kinds of
publication that can be created. It describes the SQL syntax needed for these
publications. However, each of the publications can also be created from
Sybase Central.

Creating whole-table articles


The simplest type of article is one that includes all the rows and columns of a
database table.

v To create an article that includes all the rows and columns of a


table:
1 Mark the table for replication. You do this by executing the
sp_add_remote_table procedure:
sp_add_remote_table table-name
2 Add the table to the publication. You do this by executing the
sp_add_article procedure:

371
Creating publications

sp_add_article publication-name, table-name

Example ♦ The following commands add the table SalesRep to the SalesRepData
publication:
sp_add_remote_table ’SalesRep’
sp_add_article ’SalesRepData’, ’SalesRep’
go

Creating articles containing some of the columns in a table


To create an article that includes only some of the columns from a table, you
need to list the columns that you wish to include, using sp_add_article_col.
If no columns are listed, the article includes all columns of the table.

v To create an article that includes some of the columns and all the
rows of a table:
1 Mark the table for replication. You do this by executing the
sp_add_remote_table procedure:
sp_add_remote_table table-name
go
2 Add the table to the publication. You do this by executing the
sp_add_article procedure:
sp_add_article publication-name, table-name
go
The sp_add_article procedure adds a table to a publication. By default,
all columns of the table are added to the publication. If you wish to add
only some of the columns, you must use the sp_add_article_col
procedure to specify which columns you wish to include.
3 Add individual columns to the publication. You do this by executing the
sp_add_article_col procedure for each column:
sp_add_article_col publication-name,
table-name,
column-name
go

Example ♦ The following commands add only the rep_key column of the table
SalesRep to the SalesRepData publication:
sp_add_remote_table ’SalesRep’
sp_add_article ’SalesRepData’,
’SalesRep’
sp_add_article_col ’SalesRepData’,
’SalesRep’,

372
Chapter 16 SQL Remote Design for Adaptive Server Enterprise

’rep_key’
go

Creating articles containing some of the rows in a table


There are two ways of including only some of the rows from a table in an
article:
♦ WHERE clause You can use a WHERE clause to include a subset of
rows in an article. All subscribers to the publication containing this
article receive the rows that satisfy the WHERE clause.
♦ subscription column You can use a subscription column to include a
different set of rows in different subscriptions to publications containing
the article.

Allowed clauses In SQL Remote for Adaptive Server Enterprise, the following limitations
apply to each of these cases:
♦ WHERE clause limitations The only form of WHERE clause
supported is the following:
WHERE column-name IS NOT NULL.
♦ Subscription column SQL Remote for Adaptive Server Anywhere
supports expressions other than column names. For Adaptive Server
Enterprise, the subscription expression must be a column name.

When to use You should use a subscription expression when different subscribers to a
WHERE and publication are to receive different rows from a table. The subscription
SUBSCRIBE BY expression is the most powerful method of partitioning tables.

Creating an article using a WHERE clause


The WHERE clause is used to exclude a set of rows from all subscriptions to
a publication.

v To create an article using a WHERE clause:


1 If you have not already done so, mark the table for replication. You do
this by executing the sp_add_remote_table procedure:
sp_add_remote_table table_name
2 Add the table to the publication. You do this by executing the
sp_add_article procedure: Specify the column name corresponding to
the WHERE column IS NOT NULL clause in the third argument to
the procedure:

373
Creating publications

sp_add_article publication_name,
table_name,
column_name
Do not specify IS NOT NULL; it is implicit. Specify the column name
only.
3 If you wish to include only a subset of the columns in the table, specify
the columns using the sp_add_article_col procedure. You must include
the column specified in your WHERE clause in the article.
Example ♦ The following set of statements create a publication containing a single
article, which includes only those rows of test_table for which column
col_1 is not null:
sp_create_publication test_pub
sp_add_remote_table test_table
sp_add_article test_pub, test_table, col_1
go

Creating an article using a subscription column


The subscription column is used when rows are to be shared among many
remote databases.

v To create an article using a subscription column:


1 If you have not already done so, mark the table for replication. You do
this by executing the sp_add_remote_table procedure:
sp_add_remote_table table_name
2 Add the table to the publication. You do this by executing the
sp_add_article procedure: Specify the column name you wish to use as
a subscription expression in the fourth argument to the procedure:
sp_add_article publication_name, table_name, NULL,
column_name
You must include the NULL entry to avoid adding a WHERE clause.
3 If you wish to include only a subset of the columns in the table, specify
the columns using the sp_add_article_col procedure. You must include
the column specified in your subscription expression in the article.
Example ♦ The following set of statements create a publication containing a single
article, which supports subscriptions based on the value of column
col_1:
sp_create_publication test_pub
sp_add_remote_table test_table
sp_add_article test_pub,

374
Chapter 16 SQL Remote Design for Adaptive Server Enterprise

test_table,
NULL,
col_1
go

Notes on articles
♦ You can combine a WHERE clause and a subscription expression in an
article.
♦ All columns in the primary key must be included in any article.
♦ You must not include a subset of columns in an article unless either:
♦ The remaining columns have default values or allow NULLs.
♦ No inserts are carried out at remote databases. Updates would not
cause problems as long as they do not change primary key values.
If you include a subset of columns in an article in situations other than
these, INSERT statements at the consolidated database will fail.

375
Publication design for Adaptive Server Enterprise

Publication design for Adaptive Server


Enterprise
Once you understand how to create simple publications, you must think
about proper design of publications. This section describes the issues
involved in designing publications, and how to take steps towards sound
design.

Design issues overview


Each subscription A remote database shares with the consolidated database the information in
must be a their subscriptions. The subscription is both a subset of the relational
complete relational database held at the consolidated site, and also a complete relational database
database at the remote site. The information in the subscription is therefore subject to
the same rules as any other relational database:
♦ Foreign key relationships must be valid For every entry in a foreign
key, a corresponding primary key entry must exist in the database.
The database extraction utility ensures that the CREATE TABLE
statements for remote databases do not have foreign keys defined to
tables that do not exist remotely.
♦ Primary key uniqueness must be maintained There is no way of
checking what new rows have been entered at other sites, but not yet
replicated. The design must prevent users at different sites adding rows
with identical primary key values, as this would lead to conflicts when
the rows are replicated to the consolidated database.

Transaction The data in the dispersed database (which consists of the consolidated
integrity must be database and all remote databases) must maintain its integrity in the face of
maintained in the updates at all sites, even though there is no system-wide locking mechanism
absence of locking for any particular row.
♦ Locking conflicts must be prevented or resolved In a SQL Remote
installation, there is no method for locking rows across all databases to
prevent different users from altering the rows at the same time. Such
conflicts must be prevented by designing them out of the system or must
be resolved in an appropriate manner at the consolidated database.
These key features of relational databases must be incorporated into the
design of your publications and subscriptions. This section describes
principles and techniques for sound design.

376
Chapter 16 SQL Remote Design for Adaptive Server Enterprise

Conditions for valid articles


All columns in the primary key must be included in the article.
Supporting For INSERT statements at a remote database to replicate correctly to the
INSERTS at consolidated database, you can exclude from an article only columns that can
remote databases be left out of a valid INSERT statement. These are:
♦ Columns that allow NULL.
♦ Columns that have defaults.
If you exclude any column that does not satisfy one of these requirements,
INSERT statements carried out at a remote database will fail when replicated
to the consolidated database.

Consolidated ID Rep Dept


INSERT 1 Ann 101
INTO SalesRep (ID, Rep) Insert fails
VALUES (3, ’Shih’ ) 2 Marc 101
3 Shih X

Remote ID Rep
INSERT 1 Ann Insert
INTO SalesRep (ID, Rep)
VALUES (3, ’Shih’ ) 2 Marc succeeds
3 Shih

Conditions on rows There are two ways of including only some of the rows in a publication:
♦ WHERE clause You can use a WHERE clause to include a subset of
rows in an article. All subscribers to the publication containing this
article receive the rows that satisfy the WHERE clause.
In SQL Remote for Adaptive Server Enterprise, the only supported
WHERE clause is
WHERE column-name IS NOT NULL
♦ Subscription columns You can use a subscription column to include
a different set of rows in different subscriptions to publications
containing the article.
$ For more information on restrictions on rows, see "Creating articles
containing some of the rows in a table" on page 373.

377
Partitioning tables that do not contain the subscription column

Partitioning tables that do not contain the


subscription column
In many cases, the rows of a table need to be partitioned even when the
subscription column does not exist in the table. This section describes how to
handle this case, using an example.

The Contact example


The Contact database illustrates why and how to partition tables that do not
contain the subscription column.
Example Here is a simple database that illustrates the problem. We call this database
the Contact database, because it contains a Contact table in addition to the
two tables described earlier in this chapter.

Contact
contact_key char(10)
name char(40)
cust_key char(12)

cust_key = cust_key

Customer
SalesRep
cust_key char(12) rep_key =
rep_key char(5)
name char(40) rep_key
name char(40)
rep_key char(5)

Each sales representative sells to several customers. At some customers there


is a single contact, while other customers have several contacts.
The tables in the The three tables are described in more detail as follows:
database

378
Chapter 16 SQL Remote Design for Adaptive Server Enterprise

Table Description
SalesRep All sales representatives that work for the company. The
SalesRep table has the following columns:
♦ rep_key An identifier for each sales representative. This is
the primary key.
♦ name The name of each sales representative.
The SQL statement creating this table is as follows:
CREATE TABLE SalesRep (
rep_key CHAR(12) NOT NULL,
name CHAR(40) NOT NULL,
PRIMARY KEY (rep_key)
)
go
Customer All customers that do business with the company. The Customer
table includes the following columns:
♦ cust_key An identifier for each customer. This is the primary
key.
♦ name The name of each customer.
♦ rep_key An identifier for the sales representative in a sales
relationship. This is a foreign key to the SalesRep table.

The SQL statement creating this table is as follows:


CREATE TABLE Customer (
cust_key CHAR(12) NOT NULL,
name CHAR(40) NOT NULL,
rep_key CHAR(12) NOT NULL,
FOREIGN KEY ( rep_key )
REFERENCES SalesRep,
PRIMARY KEY (cust_key)
)
go

379
Partitioning tables that do not contain the subscription column

Table Description
Contact All individual contacts that do business with the company. Each
contact belongs to a single customer. The Contact table includes
the following columns:
♦ contact_key An identifier for each contact. This is the
primary key.
♦ name The name of each contact.
♦ cust_key An identifier for the customer to which the contact
belongs. This is a foreign key to the Customer table.

The SQL statement creating this table is:


CREATE TABLE Contact (
contact_key CHAR(12) NOT NULL,
name CHAR(40) NOT NULL,
cust_key CHAR(12) NOT NULL,
FOREIGN KEY (cust_key)
REFERENCES Customer,
PRIMARY KEY (contact_key)
)
go

Replication goals The goals of the design are to provide each sales representative with the
following information:
♦ The complete SalesRep table.
♦ Those customers assigned to them, from the Customer table.
♦ Those contacts belonging to the relevant customers, from the Contact
table.
♦ Maintenance of proper information when Sales Representative territories
are realigned.

Territory realignment in the Contact example


In territory realignment, rows are reassigned among subscribers. In the
current example, territory realignment involves reassigning customers among
the sales representatives. It is carried out by updating the rep_key column of
the Customer table.
The UPDATE is replicated as an INSERT or a DELETE to the old and new
sales representatives, respectively, so that the customer row is properly
transferred to the new sales representative.

380
Chapter 16 SQL Remote Design for Adaptive Server Enterprise

No log entries for When a customer is reassigned, the Contact table is unaffected. There are no
the Contact table changes to the Contact table, and consequently no entries in the transaction
when territories log pertaining to the Contact table. In the absence of this information,
realigned SQL Remote cannot reassign the rows of the Contact table along with the
Customer. This failure would cause referential integrity problems: the
Contact table at the remote database of the old sales representative contains
a cust_key value for which there is no longer a Customer.
In this section, we describe how to reassign the rows of the Contact table.

Partitioning the Customer table in the Contact example


The Customer table can be partitioned using the rep_key value as a
subscription column. A publication that includes the SalesRep and
Customer tables would be as follows:
exec sp_add_remote_table ’SalesRep’
exec sp_add_remote_table ’Customer’
go
exec sp_create_publication ’SalesRepData’
go
exec sp_add_article ’SalesRepData’, ’SalesRep’
exec sp_add_article SalesRepData,
Customer, NULL,
’rep_key’
go

Adding a subscription-list column to the Contact table


The Contact table must also be partitioned among the sales representatives,
but contains no reference to the sales representative rep_key value.
Add a subscription- To solve this problem in Adaptive Server Enterprise, you must add a column
list column to the Contact table containing a comma-separated list of subscription
values to the row. ( In the present case, there can only be a single
subscription value.) The column can be maintained using triggers, so that
applications against the database are unaffected by the presence of the
column. We call this column a subscription-list column.
When a row in the Customer table is inserted, updated or deleted, a trigger
updates rows in the Contact table. In particular, the trigger updates the
subscription-list column. As the Contact table is marked for replication, the
before and after image of the row is recorded in the log.

381
Partitioning tables that do not contain the subscription column

Log entries are values, not subscribers


Although in this case the values entered correspond to subscribers, it is
not a list of subscribers that is entered in the log. The server handles only
information about publications, and the Message Agent handles all
information about subscribers. The values entered in the log are for
comparison to the subscription value in each subscription. For example, if
rows of a table were divided among sales representatives by state or
province, the state or province value would be entered in the transaction
log.

A subscription-list column is a column added to a table for the sole purpose


of holding a comma-separated list of subscribers. In the present case, there
can only be a single subscriber to each row of the Contact table, and so the
subscription-list column holds only a single value.
$ For a discussion of the case where the subscription-list column can hold
many values, see "Sharing rows among several subscriptions" on page 386.
Contact table In the case of the Contact table, the table definition would be changed to the
definition following:
CREATE TABLE Contact (
contact_key CHAR( 12 ) NOT NULL,
name CHAR( 40 ) NOT NULL,
cust_key CHAR( 12 ) NOT NULL,
subscription_list CHAR( 12 ) NULL,
FOREIGN KEY ( cust_key )
REFERENCES Customer ( cust_key ),
PRIMARY KEY ( contact_key )
)
go
The additional column is created allowing NULL, so that existing
applications can continue to work against the database without change.
The subscription_list column holds the rep_key value corresponding to the
row with primary key value cust_key in the Customer table. A set of triggers
handles maintenance of the subscription_list column.

382
Chapter 16 SQL Remote Design for Adaptive Server Enterprise

Contact Customer
contact subscription
cust_key _list cust_key rep_key
_key
con1 cust101 rep1 cust101 rep1

con2 cust101 rep1 cust102 rep1

con3 cust102 rep1 cust103 rep2

con4 cust103 rep2 cust104 rep3


con5 cust104 rep3

$ For an Adaptive Server Anywhere consolidated database, the solution


is different. For more information, see "Partitioning tables that do not contain
the subscription expression" on page 330.

Maintaining the subscription-list column


In order to keep the subscription_list column up to date, triggers are needed
for the following operations:
♦ INSERT on the Contact table.
♦ UPDATE on the Contact table.
♦ UPDATE on the Customer table.
The UPDATE of the Customer table addresses the territory realignment
problem, where customers are assigned to different Sales Reps.
An INSERT trigger The trigger for an INSERT on the Contact table sets the subscription_list
for the Contact value to the corresponding rep_key value from the Customer table:
table CREATE TRIGGER set_contact_sub_list
ON Contact
FOR INSERT
AS
BEGIN
UPDATE Contact
SET Contact.subscription_list = (
SELECT rep_key
FROM Customer
WHERE Contact.cust_key = Customer.cust_key )
WHERE Contact.contact_key IN (
SELECT contact_key
FROM inserted
)
END

383
Partitioning tables that do not contain the subscription column

The trigger updates the subscription_list column for those rows being
inserted; these rows being identified by the subquery
SELECT contact_key
FROM inserted

An UPDATE The trigger for an UPDATE on the Contact table checks to see if the
trigger for the cust_key column is changed, and if it has updates the subscription_list
Contact table column.
CREATE TRIGGER update_contact_sub_list
ON Contact
FOR UPDATE
AS
IF UPDATE ( cust_key )
BEGIN
UPDATE Contact
SET subscription_list = Customer.rep_key
FROM Contact, Customer
WHERE Contact.cust_key=Customer.cust_key
END
The trigger is written using a join; a subquery could also have been used.
An UPDATE The following trigger handles UPDATES of customers, transferring them to
trigger for the a new Sales Rep:
Customer table CREATE TRIGGER transfer_contact_with_customer
ON Customer
FOR UPDATE
AS
IF UPDATE ( rep_key )
BEGIN
UPDATE Contact
SET Contact.subscription_list = (
SELECT rep_key
FROM Customer
WHERE Contact.cust_key = Customer.cust_key )
WHERE Contact.contact_key IN (
SELECT cust_key
FROM inserted
)
END

Tuning extraction performance


When extracting or synchronizing a user, the subscription-list column can
cause performance problems as it necessitates a full table scan.

384
Chapter 16 SQL Remote Design for Adaptive Server Enterprise

If you are extracting databases for many users, and performance is a problem
for you, you can use a subscription view to improve performance. The view
must contain a subquery, which is used for extraction and synchronization
only, and is ignored during log scanning. The tables involved still need to
have triggers defined to maintain the subscription-list column.

v To create a subscription view:


1 Design a query that uses a subquery to select the proper rows for a
subscription from a table.
For example, continuing the example from the preceding sections, the
following query selects the rows of the Contact table for a user
subscribed by rep_key value rep5:
SELECT *
FROM Contact
WHERE ’rep5’ = (SELECT rep_key
FROM Customer
WHERE cust_key = Contact.cust_key )
2 Create a view that contains this subquery. For example:
CREATE VIEW Contact_sub_view AS
SELECT *
FROM dbo.Contact
WHERE ’repxx’ = ( SELECT rep_key
FROM dbo.Customer
WHERE cust_key = dbo.Contact.cust_key )
In this view definition, it does not matter what value you use on the left
hand side of the WHERE clause (repxx in the example above). The
replication tools use the subquery for extraction and synchronization
only. Rows for which the SUBSCRIBE BY value is equal to the
subquery result set are extracted or synchronized.
3 Give the name of the view as a parameter to sp_add_article or
sp_modify_article:
exec sp_add_article SalesRepData,
’Contact’,
NULL,
’subscription_list’,
’Contact_sub_view’
The subscription_list column is used for log scanning and the subquery is
used for extraction and synchronization.
$ For more information, see "Tuning extraction performance for
shared rows" on page 391, "sp_add_article procedure" on page 613, and
"sp_modify_article procedure" on page 628.

385
Sharing rows among several subscriptions

Sharing rows among several subscriptions


There are cases where a row may need to be included in several
subscriptions. For example, if instead of the many-to-one relationship
between customers and sales representatives that we had above, we may
have a many-to-many relationship.

The Policy example


The Policy database illustrates why and how to partition tables when there is
a many-to-many relationship in the database.
Example database Here is a simple database that illustrates the problem.

Customer Policy SalesRep

cust_key policy_key rep_key

name cust_key name

rep_key

The Policy table has a row for each of a set of policies. Each policy is drawn
up for a customer by a particular sales representative. There is a many-to-
many relationship between customers and sales representatives, and there
may be several policies drawn up between a particular rep/customer pair.
Any row in the Customer table may need to be shared with none, one, or
several sales representatives.

Solving the problem


To support this case, you need to write triggers to build a comma-delimited
list of values to store in a redundant subscription-list column of the Customer
table, and include this column as the subscription column when adding the
Customer table to the publication. The row is shared with any subscription
for which the subscription value matches any of the values in the
subscription-list column.
The database, with the subscription-list column included, is as follows:

386
Chapter 16 SQL Remote Design for Adaptive Server Enterprise

Customer Policy SalesRep

cust_key policy_key rep_key

name cust_key name

subscription_list rep_key

Adaptive Server Enterprise VARCHAR columns are limited to 255


characters, and this limits the number of values that can be stored in the
comma-delimited list.
Table definitions The table definitions are as follows:
CREATE TABLE SalesRep (
rep_key CHAR( 12 ) NOT NULL,
name CHAR( 40 ) NOT NULL,
PRIMARY KEY ( rep_key )
)
go
CREATE TABLE Customer (
cust_key CHAR( 12 ) NOT NULL,
name CHAR( 40 ) NOT NULL,
subscription_list VARCHAR( 255 ) NULL,
PRIMARY KEY ( cust_key )
)
go
CREATE TABLE Policy (
policy_key INTEGER NOT NULL,
cust_key CHAR( 12 ) NOT NULL,
rep_key CHAR( 12 ) NOT NULL,
FOREIGN KEY ( cust_key )
REFERENCES Customer (cust_key ),
FOREIGN KEY (rep_key )
REFERENCES SalesRep ( rep_key ),
PRIMARY KEY (policy_key)
)

Notes: ♦ The subscription_list column in the Customer table allows NULLs so


that customers can be added who do not have any sales representatives
in the subscription_list column.

The publication
The publication for this database can be created by the following set of
statements:
//Mark the tables for replication
exec sp_add_remote_table ’SalesRep’
exec sp_add_remote_table ’Policy’
exec sp_add_remote_table ’Customer’

387
Sharing rows among several subscriptions

go

// Create an empty publication


exec sp_create_publication ’SalesRepData’

//Add the Sales Rep table to the publication


exec sp_add_article ’SalesRepData’, ’SalesRep’

//Add the Policy table to the publication


exec sp_add_article ’SalesRepData’, ’Policy’, NULL,
’rep_key’

// Add the Customer table to the publication.


// Subscribe by the subscription_list column
// Exclude the subscription_list column
exec sp_add_article ’SalesRepData’, ’Customer’, NULL,
’subscription_list’
exec sp_add_article_col ’SalesRepData’, ’Customer’,
’cust_key’
exec sp_add_article_col ’SalesRepData’, ’Customer’,
’name’
go

Subscriptions to this publication take the following form:


exec sp_subscription ’create’,
’SalesRepData’,
’userID’,
’rep_key’
go
where userID identifies the subscriber, and rep_key is the subscription
column, which is the value of the rep_key column in the SalesRep table.

Maintaining the subscription-list column


You need to write a procedure and a set of triggers to maintain the
subscription-list column added to the Customer table. This section describes
these objects.
Stored procedure The following procedure is used to build the subscription-list column, and is
called from the triggers that maintain the subscription_list column.
CREATE PROCEDURE SubscribeCustomer @cust_key CHAR(12)
AS
BEGIN
-- Rep returns the rep list for customer @cust_key
DECLARE Rep CURSOR FOR
SELECT DISTINCT RTRIM( rep_key )
FROM Policy

388
Chapter 16 SQL Remote Design for Adaptive Server Enterprise

WHERE cust_key = @cust_key


DECLARE @rep_key CHAR(12)
DECLARE @subscription_list VARCHAR(255)

-- build comma-separated list of rep_key


-- values for this Customer
OPEN Rep
FETCH Rep INTO @rep_key
IF @@sqlstatus = 0 BEGIN
SELECT @subscription_list = @rep_key
WHILE 1=1 BEGIN
FETCH Rep INTO @rep_key
IF @@sqlstatus != 0 BREAK
SELECT @subscription_list =
@subscription_list + ’,’ + @rep_key
END
END
ELSE BEGIN
SELECT @subscription_list = ’’
END

-- update the subscription_list in the


-- Customer table
UPDATE Customer
SET subscription_list = @subscription_list
WHERE cust_key = @cust_key
END

Notes: ♦ The procedure takes a Customer key as input argument.


♦ Rep is a cursor for a query that lists each of the Sales Representatives
with which the customer has a contract.
♦ The WHILE loop builds a VARCHAR(255) variable holding the
comma-separated list of Sales Representatives.
♦ The UPDATE subscription_list column of the Customer

Triggers The following trigger updates the subscription_list column of the Customer
table when a row is inserted into the Policy table.
CREATE TRIGGER InsPolicy
ON Policy
FOR INSERT
AS
BEGIN
-- Cust returns those customers inserted
DECLARE Cust CURSOR FOR
SELECT DISTINCT cust_key
FROM inserted
DECLARE @cust_key CHAR(12)

OPEN Cust

389
Sharing rows among several subscriptions

-- Update the rep list for each Customer


-- with a new rep
WHILE 1=1 BEGIN
FETCH Cust INTO @cust_key
IF @@sqlstatus != 0 BREAK
EXEC SubscribeCustomer @cust_key
END
END

The following trigger updates the subscription_list column of the Customer


table when a row is deleted from the Policy table.
CREATE TRIGGER DelPolicy
ON Policy
FOR DELETE
AS
BEGIN
-- Cust returns those customers deleted
DECLARE Cust CURSOR FOR
SELECT DISTINCT cust_key
FROM deleted
DECLARE @cust_key CHAR(12)

OPEN Cust
-- Update the rep list for each Customer
-- losing a rep
WHILE 1=1 BEGIN
FETCH Cust INTO @cust_key
IF @@sqlstatus != 0 BREAK
EXEC SubscribeCustomer @cust_key
END
END

Excluding the The subscription-list column should be excluded from the publication, as
subscription-list inclusion of the column leads to excessive updates being replicated.
column from the
For example, consider what happens if there are many policies per customer.
publication
If a new Sales Representative is assigned to a customer, a trigger fires to
update the subscription-list column in the Customer table. If the subscription-
list column is part of the publication, then one update for each policy will be
replicated to all sales reps that are assigned to this customer.
Triggers at the The values in the subscription-list column are maintained by triggers. These
consolidated triggers fire at the consolidated database when the triggering inserts or
database only updates are applied by the Message Agent. The triggers must be excluded
from the remote databases, as they maintain a column that does not exist.
You can use the sp_user_extraction_hook procedure to exclude only certain
triggers from a remote database on extraction. The procedure is called as the
final part of an extraction. By default, it is empty.

390
Chapter 16 SQL Remote Design for Adaptive Server Enterprise

v To customize the extraction procedure to omit certain triggers:


1 Ensure the quoted_identifier option is set to ON:
set quoted_identifier on
go
2 Any temporary tables referenced in the procedure must exist, or the
CREATE PROCEDURE statement will fail. The temporary tables
referenced in the following procedure are available in the ssremote.sql
script. Copy any required table definitions from the script and execute
the CREATE TABLE statements, so they exist on the current
connection, before creating the procedure.
3 Create the following procedure:
CREATE PROCEDURE sp_user_extraction_hook
AS
BEGIN
-- We do not want to extract the INSERT and
-- DELETE triggers created on the Policy table
-- that maintain the subscription_list
-- column, since we do not include that
-- column in the publication.
-- If these objects were extracted the
-- INSERTs would fail on the remote database
-- since they reference a column
-- ( subscription_list ) that does not exist.
DELETE FROM #systrigger
WHERE table_id = object_id( ’Policy’ )
-- Do not create any procedures
DELETE FROM #sysprocedure
WHERE proc_name = ’SubscribeCustomer’
END
go

Tuning extraction performance for shared rows


When extracting or synchronizing a user, the subscription-list column can
cause performance problems as it necessitates a full table scan.
If you are extracting databases for many users, and performance is a problem
for you, you can use a subscription view to improve performance. The view
must contain a subquery, which is used for extraction and synchronization
only, and is ignored during log scanning. The tables involved still need to
have triggers defined to maintain the subscription-list column.

391
Sharing rows among several subscriptions

v To create a subscription view:


1 Design a query that uses a subquery to select the proper rows for a
subscription from a table.
For example, continuing the example from the preceding sections, the
following query selects the rows of the Contact table for a user
subscribed by rep_key value rep5:
SELECT *
FROM Contact
WHERE ’rep5’ = (SELECT rep_key
FROM Customer
WHERE cust_key = Contact.cust_key )
2 Create a view that contains this subquery. For example:
CREATE VIEW Customer_sub_view AS
SELECT *
FROM dbo.Customer
WHERE ’repxx’ IN ( SELECT rep_key
FROM dbo.Policy
WHERE dbo.Policy.cust_key = dbo.Customer.cust_key
)
In this view definition, it does not matter what value you use on the left
hand side of the WHERE clause (repxx in the example above). The
replication tools use the subquery for extraction and synchronization
only. Rows for which the SUBSCRIBE BY value is in the subquery
result set are extracted or synchronized.
3 Give the name of the view as a parameter to sp_add_article or
sp_modify_article:
exec sp_add_article SalesRepData,
’Customer’,
NULL,
’subscription_list’,
’Customer_sub_view’
The subscription_list column is used for log scanning and the subquery is
used for extraction and synchronization.
$ For more information, see "Tuning extraction performance" on
page 384, "sp_add_article procedure" on page 613, and
"sp_modify_article procedure" on page 628.

392
Chapter 16 SQL Remote Design for Adaptive Server Enterprise

Using the Subscribe_by_remote option with many-to-many


relationships
When the SUBSCRIBE_BY_REMOTE option is ON, operations that arrive
from remote databases on rows with a subscribe by value of NULL or ’’ will
assume the remote user is subscribed to the row. By default, the
SUBSCRIBE_BY_REMOTE option is set to ON. In most cases, this setting
is the desired setting.
The SUBSCRIBE_BY_REMOTE option solves a problem that otherwise
would arise with publications including the Policy example. This section
describes how the option automatically avoids the problem.
The database uses a subscription-list column for the Customer table, because
each Customer may belong to several Sales Reps:
Marc Dill is a Sales Rep who has just arranged a policy with a new customer.
He inserts a new Customer row and also inserts a row in the Policy table to
assign the new Customer to himself. Assuming that the subscription-list
column is not included in the publication, the operation at Marc’s remote
database is as follows:

Customer Policy SalesRep

cust1010 pol2345 195

cust_name cust1010 Marc Dill

195

As the INSERT of the Customer row is carried out by the Message Agent at
the consolidated database, Adaptive Server Enterprise records the
subscription value in the transaction log, at the time of the INSERT.
Later, when the Message Agent scans the log, it builds a list of subscribers to
the new row, using the subscription value stored in the log, and Marc Dill is
not on that list. If SUBSCRIBE_BY_REMOTE were set to OFF, the result
would be that the new Customer is sent back to Marc Dill as a DELETE
operation.
As long as SUBSCRIBE_BY_REMOTE is set to ON, the Message Agent
assumes that, as the subscription-list column is NULL, the row belongs to
the Sales Rep that inserted it. As a result, the INSERT is not replicated back
to Marc Dill, and the replication system is intact.
You can use a trigger, which executes after the INSERT, to maintain the
subscription-list column.

393
Managing conflicts

Managing conflicts
An UPDATE conflict occurs when the following sequence of events takes
place:
1 User 1 updates a row at remote site 1.
2 User 2 updates the same row at remote site 2.
3 The update from User 1 is replicated to the consolidated database.
4 The update from User 2 is replicated to the consolidated database.
When the SQL Remote Message Agent replicates UPDATE statements, it
does so as a separate UPDATE for each row. Also, the message contains the
old row values for comparison. When the update from user 2 arrives at the
consolidated database, the values in the row are not those recorded in the
message.

394
Chapter 16 SQL Remote Design for Adaptive Server Enterprise

uploaded new
choose one
and old row
uploaded
values from one
row
remote table

Was this row


inserted or updated in
the remote
database?

update another row


insert
compare
old values
with matching conflict
consolidated
row
insert old values using
old_row_cursor script
values match

insert new values using


insert new row update row new_row_cursor script
using using
upload_rows upload_rows
script script execute
resolve_conflict
script

any more
uploaded rows?

no more rows

finished
inserts and updates
from this table

Default conflict By default, the UPDATE still proceeds, so that the User 2 update (the last to
resolution reach the consolidated database) becomes the value in the consolidated
database, and is replicated to all other databases subscribed to that row. In
general, the default method of conflict resolution is that the most recent
operation (in this case that from User 2) succeeds, and no report is made of
the conflict. The update from User 1 is lost.
SQL Remote also allows custom conflict resolution, using a stored procedure
to resolve conflicts in a way that makes sense for the data being changed.

395
Managing conflicts

Conflicts do not UPDATE conflicts do not apply to primary key updates. If the column being
apply to primary updated is a primary key, then when the update from User 2 arrives at the
keys consolidated database, no row will be updated.
This section describes how you can build conflict resolution into your
SQL Remote installation at the consolidated database.

How SQL Remote handles conflicts


When a conflict is SQL Remote replication messages include UPDATE statements as a set of
detected single row updates, each including the values prior to updating.
An UPDATE conflict is detected by the database server as a failure of the
values to match the rows in the database.
Conflicts are detected and resolved by the Message Agent, but only at a
consolidated database. When an UPDATE conflict is detected in a message
from a remote database, the Message Agent causes the database server to
take two actions:
1 The UPDATE is applied.
2 Any conflict resolution procedures are called.
UPDATE statements are applied even if the VERIFY clause values do not
match, whether or not there is a resolve update procedure.
$ The method of conflict resolution is different at an Adaptive Server
Anywhere consolidated database. For more information, see "How
SQL Remote handles conflicts" on page 349.

Implementing conflict resolution


This section describes what you need to do to implement custom conflict
resolution in SQL Remote.
Required objects For each table on which you wish to resolve conflicts, you must create three
database objects to handle the resolution:
♦ An old value table To hold the values that were stored in the table
when the conflicting message arrived.
♦ A remote value table To hold the values stored in the table at the
remote database when the conflicting update was applied, as determined
from the message.
♦ A stored procedure To carry out actions to resolve the conflict.

396
Chapter 16 SQL Remote Design for Adaptive Server Enterprise

These objects need to exist only in the consolidated database, as that is where
conflict resolution occurs. They should not be included in any publications.
Naming the objects When a table is marked for replication, using the sp_add_remote_table or
sp_modify_remote_table stored procedure, optional parameters specify the
names of the conflict resolution objects.
The sp_add_remote_table and sp_modify_remote_table procedures take
one compulsory argument, which is the name of the table being marked for
replication. It takes three additional arguments, which are the names of the
objects used to resolve conflicts. For example, the syntax for
sp_add_remote_table is:
exec sp_add_remote_table table_name
[ , resolve_procedure ]
[ , old_row_table ]
[ , remote_row_table ]
You must create each of the three objects resolve_procedure, old_row_table,
and remote_row_table. These three are discussed in turn.
♦ old_row_table This table must have the same column names and data
types as the table table_name, but should not have any foreign keys.
When a conflict occurs, a row is inserted into old_row_table containing
the values of the row in table_name being updated before the UPDATE
was applied. Once resolve_procedure has been run, the row is deleted.
As the Message Agent applies updates as a set of single-row updates, the
table only ever contains a single row.
♦ remote_row_table This table must have the same column names and
data types as the table table_name, but should not have any foreign keys.
When a conflict occurs, a row is inserted into remote_row_table
containing the values of the row in table_name from the remote database
before the UPDATE was applied. Once resolve_procedure has been run,
the row is deleted.
As the Message Agent applies updates as a set of single-row updates, the
table only ever contains a single row.
♦ resolve_procedure This procedure carries out whatever actions are
required to resolve a conflict, which may include altering the value in
the row or reporting values into a separate table.
Once these objects are created, you must run the sp_add_remote_table or
sp_modify_remote_table procedure to flag them as conflict resolution
objects for a table.

397
Managing conflicts

Limitations ♦ At an Adaptive Server Enterprise database, conflict resolution will not


work on a table with more than 128 columns while the
VERIFY_ALL_COLUMNS option is set to ON. Even if
VERIFY_ALL_COLUMNS is set to OFF, if an UPDATE statement
updates more than 128 columns, conflict resolution will not work.

A first conflict resolution example


In this example, conflicts in the Customer table in the two-table example
used in the tutorials are reported into a table for later review.
The database The two-table database is as follows:

Customer SalesRep
cust_key char(12) rep_key = rep_key char(5)
name char(40) rep_key name char(40)
rep_key char(5)

Goals of the The conflict resolution will report conflicts on updates to the name column
conflict resolution in the Customer table into a separate table named ConflictLog.
The conflict The conflict resolution tables are defined as follows:
resolution objects CREATE TABLE OldCustomer(
cust_key CHAR( 12 ) NOT NULL,
name CHAR( 40 ) NOT NULL,
rep_key CHAR( 5 ) NOT NULL,
PRIMARY KEY ( cust_key )
)
CREATE TABLE RemoteCustomer(
cust_key CHAR( 12 ) NOT NULL,
name CHAR( 40 ) NOT NULL,
rep_key CHAR( 5 ) NOT NULL,
PRIMARY KEY ( cust_key )
)
Each of these tables has exactly the same columns and data types as the
Customer table itself. The only difference in their definition is that they do
not have a foreign key to the SalesRep table.
The conflict resolution procedure reports conflicts into a table named
ConflictLog, which has the following definition:
CREATE TABLE ConflictLog (
conflict_key numeric(5, 0) identity not null,
lost_name char(40) not null ,
won_name char(40) not null ,
primary key ( conflict_key )

398
Chapter 16 SQL Remote Design for Adaptive Server Enterprise

)
The conflict resolution procedure is as follows:
CREATE PROCEDURE ResolveCustomer
AS
BEGIN
DECLARE @cust_key CHAR(12)
DECLARE @lost_name CHAR(40)
DECLARE @won_name CHAR(40)

// Get the name that was lost


// from OldCustomer
SELECT @lost_name=name,
@cust_key=cust_key
FROM OldCustomer

// Get the name that won


// from Customer
SELECT @won_name=name
FROM Customer
WHERE cust_key = @cust_key

INSERT INTO ConflictLog ( lost_name, won_name )


VALUES ( @lost_name, @won_name )
END
This resolution procedure does not use the RemoteCustomer table.
How the conflict The stored procedure is the key to the conflict resolution. It works as
resolution works follows:
1 Obtains the @lost_name value from the OldCustomer table, and also
obtains a primary key value so that the real table can be accessed.
The @lost_name value is the value that was overridden by the conflict-
causing UPDATE.
2 Obtains the @won_name value from the Customer table itself. This is
the value that overrode @lost_name. The stored procedure runs after
the update has taken place, which is why the value is present in the
Customer table. This behavior is different from SQL Remote for
Adaptive Server Anywhere, where conflict resolution is implemented in
a BEFORE trigger.
3 Adds a row into the ConflictLog table containing the @lost_name and
@won_name values.
4 After the procedure is run, the rows in the OldCustomer and
RemoteCustomer tables are deleted by the Message Agent. In this
simple example, the RemoteCustomer row was not used.

399
Managing conflicts

Testing the
example v To test the example:
1 Create the tables and the procedure in the consolidated database, and add
them as conflict resolution objects to the Customer table.
2 Insert and commit a change at the consolidated database. For example:
UPDATE Customer
SET name = ’Sea Sports’
WHERE cust_key=’cust1’
go
COMMIT
go
3 Insert and commit a different change to the same line at the remote
database. For example:
UPDATE Customer
SET name = ’C Sports’
WHERE cust_key=’cust1’
go
COMMIT
go
4 Replicate the change from the remote to the consolidated database, by
running the Message Agent at the remote database to send the message,
and then at the consolidated database to receive and apply the message.
5 At the consolidated database, view the Customer table and the
ConflictLog table. The Customer table contains the value from the
remote database:

cust_key name rep_key


cust1 C Sports rep1

The ConflictLog table has a single row, showing the conflict:

conflict_key lost_name won_name


1 Sea Sports C Sports

A second conflict resolution example


This example shows a slightly more elaborate example of resolving a
conflict, based on the same situation as the previous example, discussed in
"A first conflict resolution example" on page 398.

400
Chapter 16 SQL Remote Design for Adaptive Server Enterprise

Goals of the In this case, the conflict resolution has the following goals:
conflict resolution
♦ Disallow the update from a remote database. The previous example
allowed the update.
♦ Report the name of the remote user whose update failed, along with the
lost and won names.

The conflict In this case, the ConflictLog table has an additional column to record the
resolution objects user ID of the remote user. The table is as follows:
CREATE TABLE ConflictLog (
conflict_key numeric(5, 0) identity not null,
lost_name char(40) not null ,
won_name char(40) not null ,
remote_user char(40) not null ,
primary key ( conflict_key )
)
The stored procedure is more elaborate. As the update will be disallowed,
rather than allowed, the lost_name value now refers to the value arriving in
the message. It is first applied, but then the conflict resolution procedure
replaces it with the value that was previously present.
The stored procedure uses data from the temporary table #remote. In order
to create a procedure that references a temporary table you first need to
create that temporary table. The statement is as follows:
CREATE TABLE #remote (
current_remote_user varchar(128),
current_publisher varchar(128)
)
This table is created in TEMPDB, and exists only for the current session. The
Message Agent creates its own #remote table when it connects, and uses it
when the procedure is executed.
CREATE PROCEDURE ResolveCustomer
AS
BEGIN
DECLARE @cust_key CHAR(12)
DECLARE @lost_name CHAR(40)
DECLARE @won_name CHAR(40)
DECLARE @remote_user varchar(128)

-- Get the name that was present before


-- the message was applied, from OldCustomer
-- This will "win" in the enx
SELECT @won_name=name,
@cust_key=cust_key
FROM OldCustomer

401
Managing conflicts

-- Get the name that was applied by the


-- Message Agent from Customer. This will
-- "lose" in the end
SELECT @lost_name=name
FROM Customer
WHERE cust_key = @cust_key

-- Get the remote user value from #remote


SELECT @remote_user = current_remote_user
FROM #remote

-- Report the problem


INSERT INTO ConflictLog ( lost_name,
won_name, remote_user )
VALUES ( @lost_name, @won_name, @remote_user )

-- Disallow the update from the Message Agent


-- by resetting the row in the Customer table
UPDATE Customer
SET name = @won_name
WHERE cust_key = @cust_key

END

Notes There are several points of note here:


♦ The user ID of the remote user is stored by the Message Agent in the
current_remote_user column of the temporary table #remote.
♦ The UPDATE from the Message Agent is applied before the procedure
runs, so the procedure has to explicitly replace the values. This is
different from the case in SQL Remote for Adaptive Server Anywhere,
where conflict resolution is carried out by BEFORE triggers.

Testing the
example v To test the example:
1 Create the tables and the procedure in the consolidated database, and add
them as conflict resolution objects to the Customer table.
2 Insert and commit a change at the consolidated database. For example:
UPDATE Customer
SET name = ’Consolidated Sports’
WHERE cust_key=’cust1’
go
COMMIT
go
3 Insert and commit a different change to the same line at the remote
database. For example:
UPDATE Customer
SET name = ’Field Sports’

402
Chapter 16 SQL Remote Design for Adaptive Server Enterprise

WHERE cust_key=’cust1’
go
COMMIT
go
4 Replicate the change from the remote to the consolidated database, by
running the Message Agent at the remote database to send the message,
and then at the consolidated database to receive and apply the message.
5 At the consolidated database, view the Customer table and the
ConflictLog table. The Customer table contains the value from the
consolidated database:

cust_key name rep_key


cust1 Consolidated Sports rep1

The ConflictLog table has a single row, showing the conflict and
recording the value entered at the remote database:

conflict_key lost_name won_name remote_user


1 Field Sports Consolidated Sports field_user

6 Run the Message Agent again at the remote database. This receives the
corrected update from the consolidated database, so that the name of the
customer is set to Consolidated Sports here as well.

Designing to avoid referential integrity errors


The tables in a relational database are related through foreign key references.
The referential integrity constraints applied as a consequence of these
references ensure that the database remains consistent. If you wish to
replicate only a part of a database, there are potential problems with the
referential integrity of the replicated database.

Referential integrity errors stop replication


If a remote database receives a message that includes a statement that
cannot be executed because of referential integrity constraints, no further
messages can be applied to the database (because they come after a
message that has not yet been applied), including passthrough statements,
which would sit in the message queue.

By paying attention to referential integrity issues while designing


publications you can avoid these problems. This section describes some of
the more common integrity problems and suggests ways to avoid them.

403
Managing conflicts

Unreplicated Consider the following SalesRepData publication:


referenced table exec sp_add_remote_table ’SalesRep’
errors exec sp_create_publication ’SalesRepData’
exec sp_add_article ’SalesRepData’, ’SalesRep’
go

If the SalesRep table had a foreign key to another table (say, Employee) that
was not included in the publication, inserts or updates to SalesRep would fail
to replicate unless the remote database had the foreign key reference
removed.
If you use the extraction utility to create the remote databases, the foreign
key reference is automatically excluded from the remote database, and this
problem is avoided. However, there is no constraint in the database to
prevent an invalid value from being inserted into the rep_id column of the
SalesRep table, and if this happens the INSERT will fail at the consolidated
database. To avoid this problem, you could include the Employee table (or at
least its primary key) in the publication.

404
Chapter 16 SQL Remote Design for Adaptive Server Enterprise

Ensuring unique primary keys


Users at physically distinct sites can each INSERT new rows to a table, so
there is an obvious problem ensuring that primary key values are kept
unique.
If two users INSERT a row using the same primary key values, the second
INSERT to reach a given database in the replication system will fail. As
SQL Remote is a replication system for occasionally-connected users, there
can be no locking mechanism across all databases in the installation. It is
necessary to design your SQL Remote installation so that primary key errors
do not occur.
For primary key errors to be designed out of SQL Remote installations; the
primary keys of tables that may be modified at more than one site must be
guaranteed unique. There are several ways of achieving this goal. This
chapter describes a general, economical and reliable method that uses a pool
of primary key values for each site in the installation.
Overview of The primary key pool is a table that holds a set of primary key values for
primary key pools each database in the SQL Remote installation. Each remote user receives
their own set of primary key values. When a remote user inserts a new row
into a table, they use a stored procedure to select a valid primary key from
the pool. The pool is maintained by periodically running a procedure at the
consolidated database that replenishes the supply.
The method is described using a simple example database consisting of sales
representatives and their customers. The tables are much simpler than you
would use in a real database; this allows us to focus just on those issues
important for replication.

The primary key pool


The pool of primary keys is held in a separate table. The following CREATE
TABLE statement creates a primary key pool table:
CREATE TABLE KeyPool (
table_name VARCHAR(40) NOT NULL,
value INTEGER NOT NULL,
location VARCHAR(6) NOT NULL,
PRIMARY KEY (table_name, value),
)
go
The columns of this table have the following meanings:

405
Ensuring unique primary keys

Column Description
table_name Holds the names of tables for which primary key pools must be
maintained. In our simple example, if new sales representatives
were to be added only at the consolidated database, only the
Customer table needs a primary key pool and this column is
redundant. It is included to show a general solution.
value Holds a list of primary key values. Each value is unique for each
table listed in table_name.
location In some setups, this could be the same as the rep_key value of the
SalesRep table. In other setups, there will be users other than sales
representatives and the two identifiers should be distinct.

For performance reasons, you may wish to create an index on the table:
CREATE INDEX KeyPoolLocation
ON KeyPool (table_name, location, value)
go

Replicating the primary key pool


You can either incorporate the key pool into an existing publication, or share
it as a separate publication. In this example, we create a separate publication
for the primary key pool.

v To replicate the primary key pool:


1 Create a publication for the primary key pool data.
sp_create_publication ’KeyPoolData’
go
sp_add_remote_table ’KeyPool’
go
sp_add_article ’KeyPoolData’, ’KeyPool’,
NULL, ’location’
go
2 Create subscriptions for each remote database to the KeyPoolData
publication.
sp_subscription ’create’,
KeyPoolData,
field_user,
rep1
go
The subscription argument is the location identifier.

406
Chapter 16 SQL Remote Design for Adaptive Server Enterprise

In some circumstances it makes sense to add the KeyPool table to an existing


publication and use the same argument to subscribe to each publication. Here
we keep the location and rep_key values distinct to provide a more general
solution.

Filling and replenishing the key pool


Every time a user adds a new customer, their pool of available primary keys
is depleted by one. The primary key pool table needs to be periodically
replenished at the consolidated database using a procedure such as the
following:
CREATE PROCEDURE ReplenishPool AS
BEGIN
DECLARE @CurrTable VARCHAR(40)
DECLARE @MaxValue INTEGER
DECLARE EachTable CURSOR FOR
SELECT table_name, max(value)
FROM KeyPool
GROUP BY table_name
DECLARE @CurrLoc VARCHAR(6)
DECLARE @NumValues INTEGER
DECLARE EachLoc CURSOR FOR
SELECT location, count(*)
FROM KeyPool
WHERE table_name = @CurrTable
GROUP BY location
OPEN EachTable
WHILE 1=1 BEGIN
FETCH EachTable INTO @CurrTable, @MaxValue
IF @@sqlstatus != 0 BREAK
OPEN EachLoc
WHILE 1=1 BEGIN
FETCH EachLoc INTO @CurrLoc, @NumValues
IF @@sqlstatus != 0 BREAK
-- make sure there are 10 values
WHILE @NumValues < 10 BEGIN
SELECT @MaxValue = @MaxValue + 1
SELECT @NumValues = @NumValues + 1
INSERT INTO KeyPool
(table_name, location, value)
VALUES (@CurrTable, @CurrLoc, @MaxValue)
END
END
CLOSE EachLoc
END
CLOSE EachTable
END
go

407
Ensuring unique primary keys

This procedure fills the pool for each user up to ten values. You may wish to
use a larger value in a production environment. The value you need depends
on how often users are inserting rows into the tables in the database.
The ReplenishPool procedure must be run periodically at the consolidated
database to refill the pool of primary key values in the KeyPool table.
The ReplenishPool procedure requires at least one primary key value to
exist for each subscriber, so that it can find the maximum value and add one
to generate the next set. To initially fill the pool you can insert a single value
for each user, and then call ReplenishPool to fill up the rest. The following
example illustrates this for three remote users and a single consolidated user
named Office:
INSERT INTO KeyPool VALUES( ’Customer’, 40, ’rep1’ )
INSERT INTO KeyPool VALUES( ’Customer’, 41, ’rep2’ )
INSERT INTO KeyPool VALUES( ’Customer’, 42, ’rep3’ )
INSERT INTO KeyPool VALUES( ’Customer’, 43, ’Office’)
EXEC ReplenishPool
go

Cannot use a trigger to replenish the key pool


You cannot use a trigger to replenish the key pool, as no actions are
replicated to the remote database performing the original operation,
including trigger actions.

Adding new customers


When a sales representative wants to add a new customer to the Customer
table, the primary key value to be inserted is obtained using a stored
procedure. This example shows a stored procedure to supply the primary key
value, and also illustrates a stored procedure to carry out the INSERT.
The procedures takes advantage of the fact that the Sales Rep identifier is the
CURRENT PUBLISHER of the remote database.
♦ NewKey procedure The NewKey procedure supplies an integer value
from the key pool and deletes the value from the pool.
CREATE PROCEDURE NewKey
@TableName VARCHAR(40),
@Location VARCHAR(6),
@Value INTEGER OUTPUT AS
BEGIN
DECLARE @NumValues INTEGER
SELECT @NumValues = count(*),
@Value = min(value)
FROM KeyPool

408
Chapter 16 SQL Remote Design for Adaptive Server Enterprise

WHERE table_name = @TableName


AND location = @Location
IF @NumValues > 1
DELETE FROM KeyPool
WHERE table_name = @TableName
AND value = @Value
ELSE
-- Never take the last value,
-- because RestorePool will not work.
-- The key pool should be kept large
-- enough so this never happens.
SELECT @Value = NULL
END
♦ NewCustomer procedure The NewCustomer procedure inserts a
new customer into the table, using the value obtained by NewKey to
construct the primary key.
CREATE PROCEDURE NewCustomer @name VARCHAR(40),
@loc VARCHAR(6) AS
BEGIN
DECLARE @cust INTEGER
DECLARE @cust_key VARCHAR(12)

EXEC NewKey ’Customer’, @loc, @cust output


SELECT @cust_key = ’cust’ +
convert( VARCHAR(12), @cust )
INSERT INTO Customer (cust_key, name, rep_key )
VALUES ( @cust_key, @name, @loc )
END
You may want to enhance this procedure by testing the @cust value
obtained from NewKey to check that it is not NULL, and preventing the
insert if it is NULL.

Testing the key pool

v To test the primary key pool:


1 Re-extract a remote database using the field_user user ID.
2 Try this sample INSERT at the remote and consolidated sites:
EXEC NewCustomer ’Great White North’, rep1

409
Ensuring unique primary keys

Primary key pool summary


The primary key pool technique requires the following components:
♦ Key pool table A table to hold valid primary key values for each
database in the installation.
♦ Replenishment procedure A stored procedure keeps the key pool
table filled.
♦ Sharing of key pools Each database in the installation must subscribe
to its own set of valid values from the key pool table.
♦ Data entry procedures New rows are entered using a stored
procedure that picks the next valid primary key value from the pool and
delete that value from the key pool.

410
Chapter 16 SQL Remote Design for Adaptive Server Enterprise

Creating subscriptions
To subscribe to a publication, each subscriber must be granted REMOTE
permissions and a subscription must also be created for that user. The details
of the subscription are different depending on whether or not the publication
uses a subscription column.
Subscriptions with To subscribe a user to a publication, if that publication has no subscription
no subscription column, you need the following information:
column
♦ User ID The user who is being subscribed to the publication. This user
must have been granted remote permissions.
♦ Publication name The name of the publication to which the user is
being subscribed.
The following statement creates a subscription for a user ID SamS to the
pub_orders_samuel_singer publication, which was created without using a
subscription column:
sp_subscription ’create’,
’pub_orders_samuel_singer’,
’SamS’

Subscriptions with To subscribe a user to a publication, if that publication does have a


a subscription subscription column, you need the following information:
column
♦ User ID The user who is being subscribed to the publication. This user
must have been granted remote permissions.
♦ Publication name The name of the publication to which the user is
being subscribed.
♦ Subscription value The value that is to be tested against the
subscription column of the publication. For example, if a publication has
the name of a column containing an employee ID as a subscription
column, the value of the employee ID of the subscribing user must be
provided in the subscription. The subscription value is always a string.
The following statement creates a subscription for Samuel Singer (user ID
SamS, employee ID 856) to the pub_orders publication, defined with a
subscription column sales_rep, requesting the rows for Samuel Singer’s own
sales:
sp_subscription create,
pub_orders,
SamS,
’856’

411
Creating subscriptions

Starting a In order to receive and apply updates properly, each subscriber needs to have
subscription an initial copy of the data. The synchronization process is discussed in
"Synchronizing databases" on page 417.

412
C H A P T E R 1 7

Deploying and Synchronizing Databases

About this chapter This chapter describes the steps you need to take to deploy and synchronize a
SQL Remote replication installation.
Contents
Topic Page
Deployment overview 414
Test before deployment 415
Synchronizing databases 417
Using the extraction utility 419
Synchronizing data over a message system 427

413
Deployment overview

Deployment overview
When you have completed the design phase of a SQL Remote system, the
next step is to create and deploy the remote databases and applications.
Deployment tasks In some cases, deployment is a major undertaking. For example, if you have
a large number of remote users in a sales force automation system,
deployment involves the following steps:
1 Building an Adaptive Server Anywhere database for each remote user,
with their own initial copy of the data.
2 Installing the database, together with the Adaptive Server Anywhere
database server, the SQL Remote Message Agent, and client application,
on each user’s machine.
3 Ensuring that the system is properly configured, with correct user
names, Message Agent connection strings, permissions, and so on.
In the case of large-scale deployments, remote sites are most commonly
Adaptive Server Anywhere databases, and this chapter focuses on this case.
Topics covered This chapter covers the following topics:
♦ Creating remote databases Before you can deploy a SQL Remote
system, you must create a remote database for each remote site.
Most of the description focuses on creating remote Adaptive Server
Anywhere databases.
♦ Synchronizing data Synchronization of a database is the setting up of
the initial copy of data in the remote database.

414
Chapter 17 Deploying and Synchronizing Databases

Test before deployment


Thorough testing of your SQL Remote system should be carried out before
deployment, especially if you have a large number of remote sites.
When you are in the design and setup phase, you can alter many facets of the
SQL Remote setup. Altering publications, message types, writing triggers to
resolve update conflicts are all easy to do.
Once you have deployed a SQL Remote application, the situation is
different. A SQL Remote setup can be seen as a single dispersed database,
spread out over many sites, maintaining a loose form of consistency. The
data may never be in exactly the same state in all databases in the setup at
once, but all data changes are replicated as complete transactions around the
system over time. Consistency is built in to a SQL Remote setup through
careful publication design, and through the reconciliation of UPDATE
conflicts as they occur.
Upgrading and Once a SQL Remote setup is deployed and is running, it is not easy to tinker
resynchronization with. An upgrade to a SQL Remote installation needs to be carried out with
the same care as an initial deployment. This applies also to upgrading
maintenance releases of the Adaptive Server Enterprise or Adaptive Server
Anywhere database software. Any such software upgrade needs to be tested
for compatibility before deployment.
Making changes to a database schema at one database within the system can
cause failures because of incompatible database objects. The passthrough
mode does allow schema changes to be sent to some or all databases in a
SQL Remote setup, but must still be used with care and planning.
The loose consistency in the dispersed database means that updates are
always in progress: you cannot generally stop changes being made to all
databases, make some changes to the database schema, and restart.
Without careful planning, changes to a database schema will produce errors
throughout the installation, and will require all subscriptions to be stopped
and resynchronized. Resynchronization involves loading new copies of the
data in each remote database, and for more than a few subscribers is a time-
consuming process involving work interruptions and possible loss of data.

Changes to avoid on a running system


The following are examples of changes that should not be made to a
deployed and running SQL Remote setup. From the list, you will see that
there is a class of changes that are permissive, and these are generally
permissible, while other changes are restrictive, and must be avoided.

415
Test before deployment

The following changes must be avoided, except under the conditions stated:
♦ Change the publisher for the consolidated database.
♦ Make restrictive changes to tables, such as dropping a column or altering
a column to not allow NULL values. Changes that include the column or
including NULL entries may already be being sent in messages around
the SQL Remote setup, and will fail.
♦ Alter a publication. Publication definitions must be maintained at both
local and remote sites, and changes that rely on the old publication
definition may already be being sent in messages around the
SQL Remote setup.
You can make permissive changes, such as adding a new table or
column, as long as you use passthrough to ensure that the new table or
column exists in the remote database and in the publication at the remote
database.
♦ Drop a subscription. This can be done only if you use passthrough
deletes to remove the data at the remote site.
♦ Unload and reload an Adaptive Server Anywhere database.
If an Adaptive Server Anywhere database is participating in replication,
it cannot be unloaded and reloaded without re-synchronizing the
database. Replication is based on the transaction log, and when a
database is unloaded and reloaded, the old transaction log is no longer
available. For this reason, good backup practices are especially
important when participating in replication.
An Adaptive Server Enterprise database can be unloaded and reloaded
as long as the system is quiet and the transaction log is fully scanned.
The page_id and row_id rows in the sr_queue_state table of the stable
queue must be reset.

416
Chapter 17 Deploying and Synchronizing Databases

Synchronizing databases
What is SQL Remote replication is carried out using the information in the
synchronization? transaction log, but there are two circumstances where SQL Remote deletes
all existing rows from those tables of a remote database that form part of a
publication, and copies the publication’s entire contents from the
consolidated database to the remote site. This process is called
synchronization.
When to Synchronization is used under the following circumstances:
synchronize
♦ When a subscription is created at a consolidated database a
synchronization is carried out, so that the remote database starts off with
a database in the same state as the consolidated database.
♦ If a remote database gets corrupt or gets out of step with the
consolidated database, and cannot be repaired using SQL passthrough
mode, synchronization forces the remote site database back in step with
the consolidated site.

How to Synchronizing a remote database can be done in the following ways:


synchronize
♦ Use the database extraction utility This utility creates a schema for a
remote Adaptive Server Anywhere database, and synchronizes the
remote database. This is generally the recommended procedure.
♦ Manual synchronization Synchronize the remote database manually
by loading from files, using the PowerBuilder pipeline, or some other
tool.
♦ Synchronize over the message system Synchronize the remote
database via the message system using the SYNCHRONIZE
SUBSCRIPTION statement (Adaptive Server Anywhere ) or
sp_subscription ’synchronize’ procedure (Adaptive Server Enterprise).

Caution
Do not execute SYNCHRONIZE SUBSCRIPTION or
sp_subscription ’synchronize’ at a remote database.

Mixed operating systems and database extraction


In many installations, the consolidated server will be running on a different
operating system than the remote databases.

417
Synchronizing databases

Adaptive Server Anywhere databases can be copied from one file or


operating system to another. This allows you flexibility in how you carry out
your initial synchronization of databases.
Example For example, you may be running an Adaptive Server Enterprise server on a
UNIX system that holds the consolidated database, but wish to deploy
remote databases on laptop computers running Windows 95.
In this circumstance, you have several options for the platforms on which
you extract the database, including the following, assuming you have the
requisite software:
♦ Run the extraction utility on UNIX to create the reload script and data
files. Copy the script and data files to a Windows 95 machine. Create the
Adaptive Server Anywhere databases and load them up with the schema
and data on Windows 95.
♦ Run the extraction utility on UNIX to create the reload script and data
files. Create the Adaptive Server Anywhere databases and load them up
with the schema and data on the same UNIX platform, and then copy the
database files onto Windows 95 machines for deployment.
♦ Run the extraction utility on Windows 95, and carry out all database
creation and other tasks on the Windows 95 operating system.

Notes on synchronization and extraction


♦ Extracting large numbers of subscriptions, or synchronizing
subscriptions to large, frequently-used tables, can slow down database
access for other users. You may wish to extract such subscriptions when
the database is not in heavy use. This happens automatically if you use a
SEND AT clause with a quiet time specified.
♦ Synchronization applies to an entire subscription. There is currently no
straightforward way of synchronizing a single table.
♦ For Adaptive Server Enterprise, Sybase Central does not display
subscriptions as started until the Message Agent first runs against the
database.
$ For performance tips for Adaptive Server Enterprise users using a
subscription-list column, see "Tuning extraction performance" on page 384
and "Tuning extraction performance for shared rows" on page 391.

418
Chapter 17 Deploying and Synchronizing Databases

Using the extraction utility


The extraction utility is an aid to creating remote Adaptive Server Anywhere
databases. It cannot be used to create remote Adaptive Server Enterprise
databases.
Running the The extraction utility can be accessed in the following ways:
extraction utility
♦ From Sybase Central.
♦ As a command-line utility. This is the dbxtract command-line utility
(Adaptive Server Anywhere), or the ssxtract command-line utility
(Adaptive Server Enterprise).

Caution
Do not run the Message Agent while running the extraction utility. The
results are unpredictable.

Creating a database from the reload files


The command-line utility unloads a database schema and data suitable for
building a remote Adaptive Server Anywhere database for a named
subscriber. It produces a SQL command file with default name reload.sql and
a set of data files. You can use these files to create a remote Adaptive Server
Anywhere database.

Editing of reload.sql may be needed


The database extraction utility is intended to assist in preparing remote
databases, but is not intended as a black box solution for all
circumstances. You should edit the reload.sql command file as needed
when creating remote databases.

v To create a remote database from the reload file:


1 Create an Adaptive Server Anywhere database using one of the
following:
♦ the Sybase Central Create Database wizard (located in the Utilities
folder)
♦ the dbinit command-line utility

419
Using the extraction utility

2 Connect to the database from the Interactive SQL utility, and run the
reload.sql command file. The following statement entered in the
Interactive SQL command window runs the reload.sql command file:
read path\reload.sql
where path is the path of the reload command file.
When used from Sybase Central, the extraction utility carries out the
database unloading task, in the same way that dbxtract or ssxtract does, and
then takes the additional step of creating the new database.
The extraction utility does not use a message system. The reload file
(ssxtract/dbxtract) or database (from Sybase Central) is created in a directory
accessible from the current machine. Synchronizing many subscriptions over
a message link can produce heavy message traffic and, if the message system
is not completely reliable, it may take some time for all the messages to be
properly received at the remote sites.

Before extracting a database


You must complete the following tasks before using the extraction utility at a
consolidated database.
♦ Create message types for replication.
♦ Add a publisher user ID to the database.
♦ Add remote users to the database.
♦ Add the publication to the database.
♦ Created a subscription for the remote users.
♦ If you need to specify message link parameters, you must have set them.

$ For a description of how to carry out these steps, see the tutorial in the
chapter "A Tutorial for Adaptive Server Anywhere Users" on page 241. For
a description of setting message link parameters, see "Setting message type
control parameters" on page 445.
When you use the extraction utility to create a remote database, the user for
which you are creating the database receives the same permissions they have
in the consolidated database. Further, if the user is a member of any groups
on the consolidated database, those group IDs are created in the remote
database with the permissions they have in the consolidated database.

420
Chapter 17 Deploying and Synchronizing Databases

Using the extraction utility from Sybase Central


This section describes how to extract a database for a remote user from the
current consolidated database.
When you complete the extraction wizard, it does the following on your
machine:
♦ Creates the remote database
♦ Extracts (unloads) the relevant structures and/or data from the
consolidated database to files
♦ Loads those files into the newly created remote database

v To extract a database for a remote user


1 Open the Utilities folder (located within the server folder).
2 In the right pane, double-click Extract Database.
3 Follow the instructions of the wizard.

Notes ♦ You can also access this wizard by clicking Tools➤Adaptive Server
Anywhere➤Extract Database.
♦ If you use the wizard to extract a non-running database, it is only able to
unload the structure and data for you. It cannot create the remote
database and reload it. For this reason, we recommend that you always
extract from a consolidated database that you are connected to in Sybase
Central.
♦ You can also invoke the extraction wizard for a particular database or
for a particular remote user – Sybase Central automatically fills in the
appropriate entries in the wizard.
♦ The extraction wizard always extracts (synchronizes) the remote
database using the WITH SYNCHRONIZATION option. In those rare
cases where you don't want to use this option, you must use the
DBXTRACT command-line utility instead.

For more For information about the extraction utility options, available as command-
information line options or as choices presented by the extraction wizard, see "Extraction
utility options" on page 534.

421
Using the extraction utility

Designing an efficient extraction procedure


It is very inefficient to create a large number of remote databases by running
the extraction utility for each one. You can make the process much more
efficient. This section describes one way of making the process more
efficient.
$ For performance tips for Adaptive Server Enterprise users using a
subscription-list column, see "Tuning extraction performance" on page 384
and "Tuning extraction performance for shared rows" on page 391.
There are several potential causes of inefficiency in a large-scale extraction
process:
♦ The extraction utility extracts one database at a time, including the
schema and data for each user. Commonly, many users share a common
schema, and only the data differs. The brute force method of running the
extraction utility for each user repeats large amounts of work
unnecessarily. Extracting schema and data separately can help with this
problem.
♦ Running from Sybase Central, the extraction utility creates a new
database for each user. If subscribers share a common schema, you
could create a single database, with schema but no data, and copy the
file.
♦ By default, the extraction utility runs at isolation level zero. If you are
extracting a database from an active server, you should run it at isolation
level 3 (see "Extraction utility options" on page 534) to ensure that data
in the extracted database is consistent with data on the server.
Running at isolation level 3 may hamper others’ turnaround time on the
server because of the large number of locks required. It is recommended
that you run the extraction utility when the server is not busy, or run it
against a copy of the database.

An efficient One approach that avoids these problems is as follows:


approach to
1 Make a copy of the consolidated database, and at the same time start the
extracting many
subscriptions from the live database. Messages will now start being sent
databases
to subscribers, even though they have no database and will not receive
them yet.
To start several subscriptions within a single transaction, use the
REMOTE RESET statement (Adaptive Server Anywhere ) or
sp_remote procedure (Adaptive Server Enterprise).
2 Extract the remote databases from the copy of the database. As the
database is a copy, there are no locking and concurrency problems. For a
large number of remote databases, this process may take several days.

422
Chapter 17 Deploying and Synchronizing Databases

3 As each remote database is created, it is out of date, but its user can
receive and apply messages that have been being sent from the live
consolidated database, to bring themselves up to date.
This solution interferes with the production database only during the first
step. The copy must be made at isolation level three if the database is in use,
and uses large numbers of locks. Also, the subscriptions must be started at
the same time that the copy is made. Any operations that take place between
the copy and the starting of the subscriptions would be lost, and could lead to
errors at remote databases.

Extracting groups
If the remote user is a group user ID, the extraction utility extracts all the
user IDs of members of that group. You can use this feature to all multiple
users on each remote database, using different user IDs, without requiring a
custom extraction process.
When a database is extracted for a user, all message link parameters for that
user and the groups of which the user is a member are extracted.

Limits to using the extraction utility


While the extraction utility is the recommended way of creating and
synchronizing remote databases from a consolidated databases, there are
some circumstances where it cannot be used, and you must synchronize
remote databases manually. This section describes some of those cases.
♦ Cannot create Adaptive Server Enterprise remote databases The
extraction utility can only be used for Adaptive Server Anywhere remote
databases.
♦ Additional tables at the remote database Remote databases can
have tables not present at their consolidated database as long as these
tables do not take part in replication. Of course, the extraction utility
cannot extract such tables from a consolidated database.
♦ Adaptive Server Enterprise/Adaptive Server Anywhere differences
Some features in Adaptive Server Enterprise are not present in Adaptive
Server Anywhere. The extraction utility carries out a mapping onto
similar features, but the mapping is not complete.
$ For more information on Adaptive Server Enterprise/Adaptive
Server Anywhere issues, see "Using the extraction utility for Adaptive
Server Enterprise" on page 425.

423
Using the extraction utility

♦ Extracting procedures and views By default, the extraction utility


extracts all stored procedures and views from the database. While some
of these views and procedures are likely to be required at the remote site,
others may not be required—they may refer only to parts of the database
that are not included in the remote site.
After running the extraction utility, you should edit the reload script and
remove unnecessary views and procedures.
♦ Using the extraction utility in multi-tiered setups To understand the
role of the extraction utility in multi-tiered arrangements, consider a
three-tiered SQL Remote setup.
This setup is illustrated in the following diagram.

HQ

Region 1 Region 2

Laptop 1 Laptop 2 Laptop 3

From the consolidated database at the top level, you can use the
extraction utility to create the second-level databases. You can then add
remote users to these second-level databases, and use the extraction
utility from each second-level database to create the remote databases.
However, if you have to re-extract the second-level databases from the
top-level consolidated database, you will delete the remote users that
were created, along with their subscriptions and permissions, and will
have to rebuild those users. The exception is if you resynchronize data
only, in which case you can use the extraction utility to replace the data
in the database, without replacing the schema.

424
Chapter 17 Deploying and Synchronizing Databases

Using the extraction utility for Adaptive Server Enterprise


The extraction utility for Adaptive Server Enterprise takes an Adaptive
Server Enterprise database schema, and produces an Adaptive Server
Anywhere database. There are several limitations and techniques specific to
this tool.

Adaptive Server Enterprise features unsupported in Adaptive Server Anywhere


There are some features in Adaptive Server Enterprise that are either not
supported or are only partially supported in Adaptive Server Anywhere. The
extraction utility handles some of these features partially, and some not at all.
$ For a full description of Adaptive Server Enterprise/Adaptive Server
Anywhere compatibility, see the part Transact-SQL Compatibility, in the
Adaptive Server Anywhere User’s Guide.
Features not supported in ssxtract include the following:
♦ Grouped procedures Adaptive Server Anywhere does not support
procedure groups, and they are not extracted by ssxtract.
♦ Named constraints and defaults Adaptive Server Anywhere does not
support named constraints and named defaults. Any such objects are
extracted directly as constraints and defaults that apply to a single
object, and the name is lost.
♦ Roles ssxtract extracts roles using the Adaptive Server Anywhere
concept of groups. It creates a group with the named role, and assigns
users to it.
♦ Passwords If the user for whom a database is being extracted does
not have an entry in SYSLOGINS, no password is extracted. If the user
does have a login ID, a dummy password is extracted.
♦ NCHAR, NVARCHAR These data types are extracted as CHAR and
VARCHAR, with NULLS allowed.
♦ timestamp columns Although Adaptive Server Anywhere does
provide a timestamp column, it is a different data type from that of
Adaptive Server Enterprise. Timestamp columns are not extracted.

425
Using the extraction utility

Customizing the system tables


The objects that are to be loaded into an Adaptive Server Anywhere database
are described in the system catalog. The extraction utility for Adaptive
Server Enterprise first creates a set of Adaptive Server Anywhere system
tables in TEMPDB, and fills them with data from the Adaptive Server
Enterprise catalog. It then unloads this set of tables to provide the reload
script that in turn builds an Adaptive Server Anywhere database.
There may be cases where you wish to change the content of the Adaptive
Server Anywhere system tables held in TEMPDB. SQL Remote provides a
place for you to do that.
The stored procedure that creates and fills the Adaptive Server Anywhere
system objects in TEMPDB is called sp_populate_sql_anywhere. As its
final operation, this procedure calls a procedure called
sp_user_extraction_hook. This procedure, by default, does nothing. If you
wish to customize the extraction procedure, you can do so by writing a
suitable sp_user_extraction_hook procedure.

426
Chapter 17 Deploying and Synchronizing Databases

Synchronizing data over a message system


Creating A subscription is created at a consolidated Adaptive Server Enterprise
subscriptions database using the sp_subscription procedure with a first argument of
create.
Creating a subscription defines the data to be received. It does not
synchronize a subscription (provide an initial copy of the data) or start
(exchange messages) a subscription.
Synchronizing Synchronizing a subscription causes the Message Agent to send a copy of all
subscriptions rows in the subscription to the subscriber. It assumes that an appropriate
database schema is in place. At an Adaptive Server Anywhere consolidated
database, subscriptions are synchronized using the SYNCHRONIZE
SUBSCRIPTION statement. At an Adaptive Server Enterprise consolidated
database, subscriptions are synchronized using the sp_subscription
procedure with a first argument of synchronize.
When synchronization messages are received at a subscriber database, the
Message Agent replaces the current contents of the database with the new
copy. Any data at the subscriber that is part of the subscription, and which
has not been replicated to the consolidated database, is lost. Once
synchronization is complete, the subscription is started by the Message
Agent using the START SUBSCRIPTION statement or sp_subscription
procedure with a first argument of start.

Large volume of messages may result


Synchronizing databases over a message system may lead to large
volumes of messages. In many cases, it is preferable to use the extraction
process to synchronize a database locally without placing this burden on
the message system.

Synchronizing If a remote database becomes out of step with the consolidated database, and
subscriptions cannot be brought back in step using the SQL passthrough capabilities of
during operation SQL Remote, synchronizing the subscription forces the remote database into
step with the consolidated database by copying the rows of the subscription
from the consolidated database over the contents at the remote database.

Data loss on synchronization


Any data in the remote database that is part of the subscription, but which
has not been replicated to the consolidated database, is lost when the
subscription is synchronized. You may wish to unload or back up the
remote database using Sybase Central or, for Adaptive Server Anywhere,
the dbunload utility before synchronizing the database.

427
Synchronizing data over a message system

428
C H A P T E R 1 8

SQL Remote Administration

About this chapter This chapter describes general issues and principles for administering a
running SQL Remote installation.
$ For system-specific details, see the chapters "Administering
SQL Remote for Adaptive Server Enterprise" on page 493 and
"Administering SQL Remote for Adaptive Server Anywhere" on page 471.
Contents
Topic Page
Management overview 430
Managing SQL Remote permissions 431
Using message types 441
Running the Message Agent 454
Tuning Message Agent performance 458
Encoding and compressing messages 465
The message tracking system 467

429
Management overview

Management overview
This chapter describes administration issues for SQL Remote installations.
Administration of a deployed and running SQL Remote setup is carried out
at a consolidated database.
♦ Permissions As a SQL Remote installation includes many different
physical databases, a consistent scheme for users having permissions on
remote and consolidated databases is necessary. A section of this chapter
describes the considerations you need to make when assigning users
permissions.
♦ Configuring message systems Each message system that is used in a
SQL Remote installation has control parameters and other settings that
must be set up. These settings are discussed in this chapter.
♦ The Message Agent The Message Agent is responsible for sending
and receiving messages. While some details of how the Message Agent
operates and the configuration options for it, are different for Adaptive
Server Anywhere and Adaptive Server Enterprise, some concepts and
methods are common to both. These common features are discussed
here.
♦ Message tracking Administering a SQL Remote installation means
managing large numbers of messages being handed back and forth
among many databases. A section on the SQL Remote message tracking
system is included to help you understand what the messages contain,
when they are sent, how they are applied, and so on.
♦ Log management SQL Remote obtains the data to send from the
transaction log. Consequently, proper management of the transaction
log, and proper backup procedures, are essential for a smoothly running
SQL Remote installation. While many details depend on the server you
are running, the generic issues are discussed in this chapter.
♦ Passthrough mode This is a method for directly intervening at a
remote site from a consolidated database. This method is discussed in
this chapter.

430
Chapter 18 SQL Remote Administration

Managing SQL Remote permissions


Users of a database involved in SQL Remote replication are identified by
one of the following sets of permissions:
♦ PUBLISH A single user ID in a database is identified as the publisher
for that database. All outgoing SQL Remote messages, including both
publication updates and receipt confirmations, are identified by the
publisher user ID. Every database in a SQL Remote setup must have a
single publisher user ID, as every database in a SQL Remote setup sends
messages.
♦ REMOTE All recipients of messages from the current database, or
senders of messages to the current database, who are immediately lower
on the SQL Remote hierarchy than the current database must be granted
REMOTE permissions.
♦ CONSOLIDATE At most one user ID may be granted
CONSOLIDATE permissions in a database. CONSOLIDATE
permissions identifies a database immediately above the current
database in a SQL Remote setup. Each database can have only one
consolidated database directly above it.
Information about these permissions are held in the SQL Remote system
tables, and are independent of other database permissions.

Granting and revoking PUBLISH permissions


When a database sends a message, a user ID representing that database is
included with the message to identify its source to the recipient. This user ID
is the publisher user ID of the database. A database can have only one
publisher. You can find out who the publisher is at any time in Sybase
Central by opening the SQL Remote folder.
A publisher is required even for read-only remote databases within a
replication system, as even these databases send confirmations to the
consolidated database to maintain information about the status of the
replication. The GRANT PUBLISH statement for remote Adaptive Server
Anywhere databases is carried out automatically by the database extraction
utility.
Granting and You can grant PUBLISH permissions from Sybase Central. You must
revoking PUBLISH connect to the database as a user with full system or database administrator
permissions from permissions.
Sybase Central

431
Managing SQL Remote permissions

v To create a new user as the publisher (Sybase Central):


1 Open the Users & Groups folder.
2 Double-click Add User.
3 On the first page of the wizard, enter a name and password and click
Next.
4 On the next page, ensure that the user is granted Remote DBA authority;
this enables the user ID to run the Message Agent. Then click Next.
5 On the final page, check the box identifying this user ID as the
publisher. Then click Finish to create the user.

v To make an existing user the publisher (Sybase Central):


1 Do one of the following:
♦ In the Users & Groups folder, right-click a user and choose Set as
Publisher from the popup menu.
♦ In the SQL Remote folder, double-click Set Publisher. Choose a
user in the resulting dialog and click OK to set that user as the
database publisher.
You can also revoke PUBLISH permissions from Sybase Central.

v To revoke PUBLISH permissions (Sybase Central):


1 Do one of the following:
♦ In the Users & Groups folder, right-click the user who has granted
PUBLISH permissions and choose Revoke Publisher from the
popup menu.
♦ In the SQL Remote folder, right-click the user who has granted
PUBLISH permissions and choose Revoke Publisher from the
popup menu.

Granting and For Adaptive Server Anywhere, PUBLISH permissions are granted using the
revoking PUBLISH GRANT PUBLISH statement:
permissions GRANT PUBLISH TO userid ;
[Adaptive Server
Anywhere] The userid is a user with CONNECT permissions on the current database.
For example, the following statement grants PUBLISH permissions to user
S_Beaulieu:
GRANT PUBLISH TO S_Beaulieu
The REVOKE PUBLISH statement revokes the PUBLISH permissions from
the current publisher:

432
Chapter 18 SQL Remote Administration

REVOKE PUBLISH FROM userid

Granting and For Adaptive Server Enterprise, PUBLISH permissions are granted using the
revoking PUBLISH sp_publisher procedure:
permissions sp_publisher userid
[Adaptive Server
Enterprise] The userid is a user with CONNECT permissions on the current database.
For example, the following statement grants PUBLISH permissions to user
S_Beaulieu:
exec sp_publisher ’S_Beaulieu’
go
The database is set to have no publisher by executing the sp_publisher
procedure with no argument:
exec sp_publisher
go

Notes on PUBLISH ♦ To see the publisher user ID for an Adaptive Server Anywhere database
permissions outside Sybase Central, use the CURRENT PUBLISHER special
constant. The following statement retrieves the publisher user ID:
SELECT CURRENT PUBLISHER
♦ To see the publisher user ID for an Adaptive Server Enterprise database
outside Sybase Central, use the following statement:
SELECT name
FROM sysusers
WHERE uid = ( SELECT user_id
FROM sr_publisher )
go
♦ If PUBLISH permissions is granted to a user ID with GROUP
permissions, it is not inherited by members of the group.
♦ PUBLISH permissions carry no authority except to identify the
publisher in outgoing messages.
♦ For messages sent from the current database to be received and
processed by a recipient, the publisher user ID must have REMOTE or
CONSOLIDATE permissions on the receiving database.
♦ The publisher user ID for a database cannot also have REMOTE or
CONSOLIDATE permissions on that database. This would identify
them as both the sender of outgoing messages and a recipient of such
messages.

433
Managing SQL Remote permissions

♦ Changing the user ID of a publisher at a remote database will cause


serious problems for any subscriptions that database is involved in,
including loss of information. You should not change a remote database
publisher user ID unless you are prepared to resynchronize the remote
user from scratch.
♦ Changing the user ID of a publisher at a consolidated database while a
SQL Remote setup is operating will cause serious problems, including
loss of information. You should not change the consolidated database
publisher user ID unless you are prepared to close down the SQL
Remote setup and resynchronize all remote users.

Granting and revoking REMOTE and CONSOLIDATE permissions


REMOTE and CONSOLIDATE permissions are very similar. Each database
receiving messages from the current database must have an associated user
ID on the current database that is granted one of REMOTE or
CONSOLIDATE permissions. This user ID represents the receiving database
in the current database.
Databases directly below the current database on a SQL Remote hierarchy
are granted REMOTE permissions, and the at most one database above the
current database in the hierarchy is granted CONSOLIDATE permissions.
Setting REMOTE For Adaptive Server Anywhere, the GRANT REMOTE and GRANT
and CONSOLIDATE statements identify the message system and address to
CONSOLIDATE which replication messages must be sent.
permissions
For Adaptive Server Enterprise, the sp_grant_remote procedure sets
REMOTE permissions, and the sp_grant_consolidate procedure sets
CONSOLIDATE permissions.
CONSOLIDATE permissions must be granted even from read-only remote
databases to the consolidated database, as receipt confirmations are sent back
from the remote databases to the consolidated database. The GRANT
CONSOLIDATE statement at remote Adaptive Server Anywhere databases
is executed automatically by the database extraction utility.

Granting REMOTE permissions


Each remote database must be represented by a single user ID in the
consolidated database. This user ID must be granted REMOTE permissions
to identify their user ID and address as a subscriber to publications.
Granting REMOTE permissions accomplishes several tasks:
♦ It identifies a user ID as a remote user.

434
Chapter 18 SQL Remote Administration

♦ It specifies a message type to use for exchanging messages with this user
ID.
♦ It provides an address to where messages are to be sent.
♦ It indicates how often messages should be sent to the remote user.
Granting REMOTE permissions is also referred to as adding a remote user to
the database.
Sybase Central You can add a remote user to a database using Sybase Central. Remote users
example and groups appear in two locations in Sybase Central: in the Users & Groups
folder, and in the Remote Users folder (located within the SQL Remote
folder).
By default, remote users are created with remote DBA authority. Since the
message agent for access to the remote database requires this authority, you
shouldn’t revoke it.
You cannot create a new remote user until at least one message type is
defined in the database.
While you can grant remote permissions to a group, those remote
permissions do not automatically apply to users in the group (unlike table
permissions, for example). To do this, you must explicitly grant remote
permissions to each user in the group. Otherwise, remote groups behave
exactly like remote users (and are categorized as remote users).

v To add a new user to the database as a remote user (Sybase


Central):
1 Open the Remote Users folder (located within the SQL Remote folder).
2 Double-click Add Remote User and follow the instructions in the
wizard.

v To make an existing user or group remote (Sybase Central):


1 Open the Users & Groups folder.
2 Right-click the user or group you want to make remote and choose Set
Remote from the popup menu.
3 In the resulting dialog, select the message type from the list, enter an
address, choose the frequency of sending messages, and click OK to
make the user a remote user.
$ For descriptions of the dialogs, see "Change User to a Remote User
dialog" on page 1014 of the book ASA User’s Guide and "Change Group to a
Remote Group dialog" on page 1013 of the book ASA User’s Guide.

435
Managing SQL Remote permissions

Adaptive Server The following statement grants remote permissions to user S_Beaulieu, with
Anywhere example the following options:
♦ Use an SMTP e-mail system
♦ Send messages to e-mail address s_beaulieu@acme.com:
♦ Send message daily, at 10 pm.
GRANT REMOTE TO S_Beaulieu
TYPE smtp
ADDRESS ’s_beaulieu@acme.com’
SEND AT ’22:00’

Adaptive Server The following statement grants remote permissions to user S_Beaulieu with
Enterprise example the following options:
♦ Use the file-sharing system to exchange messages.
♦ Place messages in the directory beaulieu under the address root
directory.
The address root directory (for both Adaptive Server Anywhere and
Adaptive Server Enterprise) is indicated by the SQLREMOTE
environment variable, if it is set. Alternatively, it is indicated by the
Directory setting in the FILE message control parameters (held in the
registry or INI file).
♦ Send messages every twelve hours:
exec sp_grant_remote ’S_Beaulieu’,
’file’,
’beaulieu’,
’SEND EVERY’,
’12:00’
go

Selecting a send frequency


There are three alternatives for the setting the frequency with which
messages are sent. The three alternatives are:
♦ SEND EVERY A frequency can be specified in hours and minutes.
When any user with SEND EVERY set is sent messages, all users with
the same frequency are sent messages also. For example, all remote
users who receive updates every twelve hours are sent updates at the
same times, rather than being staggered. This reduces the number of
times the Adaptive Server Anywhere transaction log or Adaptive Server
Enterprise stable queue has to be processed. You should use as few
unique frequencies as possible.

436
Chapter 18 SQL Remote Administration

SQL Remote is not intended for up-to-the-minute replication.


Frequencies of less than ten minutes are not recommended.
♦ SEND AT A time of day, in hours and minutes.
Updates are started daily at the specified time. It is more efficient to use
as few distinct times as possible than to stagger the sending times. Also,
choosing times when the database is not busy minimizes interference
with other users.
♦ Default setting (no SEND clause) If any user has no SEND AT or
SEND EVERY clause, the Message Agent sends messages every time it
is run, and then stops: it runs in batch mode.

Setting the send In Sybase Central, you can specify the send frequency in the following ways:
frequency in ♦ When you make an existing user or group remote. For more information,
Sybase Central see "Granting REMOTE permissions" on page 434.
♦ On the SQL Remote tab of the property sheet of a remote user or group.
You can access the property sheet by right-clicking the remote user or
group and choosing Properties from the popup menu. For a full
description, see "Remote Users properties" on page 1069 of the book
ASA User’s Guide.

Granting CONSOLIDATE permissions


In the remote database, the publish and subscribe user IDs are inverted
compared to the consolidated database. The subscriber (remote user) in the
consolidated database becomes the publisher in the remote database. The
publisher of the consolidated database becomes a subscriber to publications
from the remote database, and is granted CONSOLIDATE permissions.
At each remote database, the consolidated database must be granted
CONSOLIDATE permissions. When you produce a remote database by
running the database extraction utility, the GRANT CONSOLIDATE
statement is executed automatically at the remote database.
Adaptive Server The following Adaptive Server Anywhere statement grants
Anywhere example CONSOLIDATE permissions to the hq_user user ID, using the VIM e-mail
system:
GRANT CONSOLIDATE TO hq_user
TYPE vim
ADDRESS ’hq_address’
There is no SEND clause in this statement, so the default is used and
messages will be sent to the consolidated database every time the Message
Agent is run.

437
Managing SQL Remote permissions

Adaptive Server The following Adaptive Server Enterprise statement grants CONSOLIDATE
Enterprise example permissions to user hq_user, using the file message link:
exec sp_grant_consolidate ’hq_user’, ’file’, address
go

Revoking REMOTE and CONSOLIDATE permissions


A user can be removed from a SQL Remote installation by revoking their
REMOTE permissions. When you revoke remote permissions from a user or
group, you revert that user or group to a normal user/group. You also
automatically unsubscribe that user or group from all publications.
Revoking You can revoke REMOTE permissions on both Adaptive Server Enterprise
permissions from and Adaptive Server Anywhere from Sybase Central.
Sybase Central
v To revoke REMOTE permissions (Sybase Central):
1 Open either the Users & Groups folder or the Remote Users folder
(located within the SQL Remote folder).
2 Right-click the remote user or group and choose Revoke Remote from
the popup menu.

Revoking REMOTE and CONSOLIDATE permissions can be revoked from a user


permissions in using the REVOKE statement. The following statement revokes REMOTE
Adaptive Server permission from user S_Beaulieu.
Anywhere REVOKE REMOTE FROM S_Beaulieu
DBA authority is required to revoke REMOTE or CONSOLIDATE access.
Revoking REMOTE permissions can be revoked from a user using the
permissions in sp_revoke_remote procedure. This procedure takes a single argument,
Adaptive Server which is the user ID of the user. The following statement revokes REMOTE
Enterprise permission from user S_Beaulieu.
exec sp_revoke_remote ’S_Beaulieu’
go

438
Chapter 18 SQL Remote Administration

Assigning permissions in multi-tier installations


Special considerations are needed for assigning permissions in multi-tier
installations. The permissions in a three-level SQL Remote setup are
summarized in the following diagrams. In each diagram one database is
shaded; the diagram shows the permissions that need to be granted in that
database for the user ID representing each of the other databases. The phrase
"No permissions" means that the database is not granted any permissions in
the shaded database.
The following picture shows SQL Remote permissions, as granted at the
consolidated site of a three-tier installation.

Publish

Remote

no no
permissions permissions

The following picture shows SQL Remote permissions, as granted at an


internal site of a three-tier installation.

Consolidate

Publish

Remote Remote

The following picture shows SQL Remote permissions, as granted at an


internal site of a three-tier installation.

439
Managing SQL Remote permissions

no
permissions

Consolidate

no
Publish permissions

Granting the appropriate PUBLISH and CONSOLIDATE permissions at


remote databases is done automatically by the database extraction utility.

440
Chapter 18 SQL Remote Administration

Using message types


SQL Remote supports several different systems for exchanging messages.
The message systems supported by SQL Remote are:
♦ file Storage of message files in directories on a shared file system for
reading by other databases.
♦ ftp Storage of message files in directories accessible by a file transfer
protocol (ftp) link.
♦ mapi Microsoft’s messaging API (MAPI) link, used in Microsoft Mail
and other electronic mail systems.
♦ smtp Internet Simple Mail Transfer Protocol (SMTP/POP), used in
Internet e-mail.
♦ vim Lotus’s Vendor Independent Messaging (VIM), used in Lotus
Notes and cc:Mail.
A database can exchange messages using one or more of the available
message systems.
Operating system Not all message systems are supported on all operating systems for which
availability SQL Remote is available. The links are implemented as DLLs on Windows
3.x, Windows 95, and Windows NT.
$ For a listing of which message systems are supported on which
operating system, see "Supported Platforms and Message Links" on
page 675.
For more ♦ For more information on the file message system, see "The file message
information system" on page 446.
♦ For more information on the ftp message system, see "The ftp message
system" on page 447.
♦ For more information on the smtp message system, see "The SMTP
message system" on page 449.
♦ For more information on the mapi message system, see "The MAPI
message system" on page 451.
♦ For more information on the vim message system, see "The VIM
message system" on page 452.

441
Using message types

Working with message types


Each message type definition includes the type name (file, ftp, smtp, mapi,
or vim) and also the address of the publisher under that message type. The
publisher address at a consolidated database is used by the database
extraction utility as a return address when creating remote databases. It is
also used by the Message Agent to identify where to look for incoming
messages for the file system.
The address supplied with a message type definition is closely tied to the
publisher ID of the database. Valid addresses are considered in following
sections.
Before you can use a message system, you must set the publisher’s address.

Using Sybase Central to work with message types


You can create and alter message types in Sybase Central. Message types
appear in the Message Types folder (located within the SQL Remote folder).
You must have DBA authority to create and alter message types.

v To add a message type (Sybase Central):


1 Connect to a database.
2 Open the SQL Remote folder for that database.
3 Within the SQL Remote folder, open the Message Types folder.
4 Double-click Add Message Type.
5 In the resulting dialog, enter a message type name. The name should
correspond to a message-type DLL already installed in your Adaptive
Server Anywhere directory.
6 Enter a publisher address and click OK to save the definition in the
database.
If you wish to change the publisher’s address, you can do so by altering a
message type. You cannot change the name of an existing message type;
instead, you must delete it and create a new message type with the new
name.

v To alter a message type (Sybase Central):


1 Open the SQL Remote folder for a database.
2 Within the SQL Remote folder, open the Message Types folder.

442
Chapter 18 SQL Remote Administration

3 In the right pane, right-click the message type you wish to alter and
select Properties from the popup menu.
4 On the property sheet, configure the various options.
If you wish to drop a message type from the installation, you can do so.

v To drop a message type (Sybase Central):


1 Open the SQL Remote folder for a database.
2 Within the SQL Remote folder, open the Message Types folder.
3 In the right pane, right-click the message type you wish to alter and
select Delete from the popup menu.
$ See also
♦ "Property Sheet Descriptions" on page 1035 of the book ASA User’s
Guide

Using commands to work with message types

v To create a message type (SQL):


1 Make sure you have decided on an address for the publisher under the
message type.
2 Execute a CREATE REMOTE MESSAGE TYPE command.
For Adaptive Server Anywhere, the CREATE REMOTE MESSAGE
TYPE statement has the following syntax:
CREATE REMOTE MESSAGE TYPE type-name
ADDRESS address-string
For Adaptive Server Enterprise, use the sp_remote_type procedure.
This procedure takes the following arguments:
sp_remote_type type-name, address-string
In these statements, type-name is one of the message systems supported
by SQL Remote, and address-string is the publisher’s address under that
message system.
If you wish to change the publisher’s address, you can do so by altering the
message type.

v To alter a message type (SQL):


1 Make sure you have decided on a new address for the publisher under
the message type.

443
Using message types

2 Execute an ALTER REMOTE MESSAGE TYPE statement.


For Adaptive Server Anywhere, the ALTER REMOTE MESSAGE
TYPE statement has the following syntax:
ALTER REMOTE MESSAGE TYPE type-name
ADDRESS address-string
For Adaptive Server Enterprise, use the sp_remote_type procedure in
the same way as creating a message type. This procedure takes the
following arguments:
sp_remote_type type-name, address-string
In these statements, type-name is one of the message systems supported
by SQL Remote, and address-string is the publisher’s address under that
message system.
You can also drop message types if they are no longer used in your
installation. This has the effect of removing the publisher’s address from the
definition.

v To drop a message type (SQL):


♦ Execute a DROP REMOTE MESSAGE TYPE statement.
For Adaptive Server Anywhere, the DROP REMOTE MESSAGE
TYPE statement has the following syntax:
DROP REMOTE MESSAGE TYPE type-name
For Adaptive Server Enterprise, use the sp_drop_remote_type
procedure in the same way as creating a message type. This procedure
takes the following arguments:
sp_drop_remote_type type-name
In these statements, type-name is one of the message systems supported
by SQL Remote.
$ See also
♦ "CREATE REMOTE MESSAGE TYPE statement" on page 581
♦ "ALTER REMOTE MESSAGE TYPE statement" on page 578
♦ "DROP REMOTE MESSAGE TYPE statement" on page 588

444
Chapter 18 SQL Remote Administration

Setting message type control parameters


Each message link has several parameters that govern aspects of its behavior.
The parameters differ from message system to message system, but all are
managed in the same way.
When you first use the Message Agent for a particular message link, it
displays a dialog box showing a set of parameters that control the behavior of
the link. These parameters may be a user ID for the message system, a host
name where ftp messages are held, and so on. The parameters you enter are
saved by the Message Agent. You can also set these parameters explicitly.
Message link The message control parameters are held in the database. You can set the
parameters stored options as follows:
in the database
v To set a message control parameter (Adaptive Server Anywhere):
♦ Execute the following statement:
SET REMOTE link-name OPTION
[username.]option-name = option-value

v To set a message control parameter (Adaptive Server Enterprise):


♦ Execute the following statement:
exec sp_link_option link-name, [username],
option-name, option-value
You can see the current message link parameters by querying the
sys.sysremoteoptions view (Adaptive Server Anywhere) or the
sr_remoteoptions view (Adaptive Server Enterprise).

Holding the Earlier versions of this software stored the message link parameters outside
message link the database. You can still use this method, but storing the parameters inside
parameters on disk the database is recommended unless you have specific reasons to choose
otherwise.
The message link control parameters are stored in the following places:
♦ Windows 95/98 and Windows NT In the registry, at the following
location:
\\HKEY_CURRENT_USER
\Software
\Sybase
\SQL Remote
The parameters for each message link go in a key under the
SQL Remote key, with the name of the message link (4, smtp, and so
on).

445
Using message types

♦ NetWare You should create a file named dbremote.ini in the


sys:\system directory to hold the FILE system directory setting. This file
is not a Windows-format INI file: it must consist of a single line, holding
only the directory name.
For example, if the directory is user:\dbr43, then the dbremote.ini file
would contain the following:
user:\dbr43
♦ UNIX The FILE system directory setting is held in the SQLREMOTE
environment variable.
The sqlremote environment variable holds a path that can be used as an
alternative to one of the control parameters for the file sharing system.
The parameters available for each message system are discussed in the
following sections. Each section describes a single message system.
When the Message Agent loads a message link, the link uses the settings of
the current publisher or, of a setting is not specified, of groups to which the
publisher belongs. On Windows 95/98 or Windows NT, the first time a
version of the Message Agent is run that supports storing the message link
parameters in the database, it copies the link options from the registry to the
database.

The file message system


SQL Remote can be used even if you do not have a message system in place,
by using the file message system.
Addresses in the The file message system is a simple file-sharing system. A file address for a
file message remote user is a subdirectory into which all their messages are written. To
system retrieve messages from their "inbox", an application reads the messages from
the directory containing the user’s files. Return messages are sent to the
address (written to the directory) of the consolidated database.
When running as an NT service make sure that the account under which the
Message Agent is running has permissions to read and write all necessary
directories. This is often a problem when accessing network drives.
Root directory for The file system addresses are typically subdirectories of a shared directory
addresses that is available to all SQL Remote users, whether by modem or on a local
area network. Each user should have a registry entry, initialization file entry,
or SQLREMOTE environment variable pointing to the shared directory.
You can also use the file system to put the messages in directories on the
consolidated and remote machines. A simple file transfer mechanism can
then be used to exchange the files periodically to effect replication.

446
Chapter 18 SQL Remote Administration

FILE message The FILE message system uses the following control parameters:
control parameters ♦ Directory This is set to the directory under which the messages are
stored. The setting is an alternative to the SQLREMOTE environment
variable.
♦ Debug This is set to either YES or NO, with the default being NO.
When set to YES, all file system calls made by the FILE link are
displayed.
The FILE section of the sqlany.ini file (Windows 3.x) has the following
entries:
[ FILE ]
Directory=path
Debug={ yes | no }
On NetWare, you should create a file named dbremote.ini in the sys:\system
directory to hold the directory setting.

The ftp message system


Addresses for ftp In the ftp message system, messages are stored in directories under a root
directory on an ftp host. The ftp host and the root directory are specified by
message system control parameters held in the registry or initialization file,
and the address of each user is the subdirectory where their messages are
held.
$ For a list of operating systems for which ftp is supported, see
"Supported operating systems" on page 677.
FTP message The ftp message system uses the following control parameters:
control parameters ♦ host The host name of the computer where the messages are stored.
This can be a host name (such as ftp.powersoft.com) or an IP address
(such as 192.138.151.66).
♦ user The user name for accessing the ftp host.
♦ password The password for accessing the ftp host.
♦ root_directory The root directory within the ftp host site, under which
the messages are stored.
♦ port Usually not required. This is the IP port number used for the Ftp
connection.
♦ debug This is set to either YES or NO, with the default being NO.
When set to YES, debugging output is displayed.

447
Using message types

♦ active_mode This is set to either YES or NO, with the default being
NO (passive mode).

Troubleshooting ftp problems


Most problems with the FTP message link are network setup issues. This
section contains a list of tests you can try to troubleshoot problems.

Set the DEBUG message control parameter Looking over the debug
output should indicate whether you are connecting to the FTP server. If you
are connecting, it will indicate which FTP commands are failing.

Ping the ftp server If the FTP link is not able to connect to the FTP
server try testing your systems network configuration; If your system has the
ping command try typing the following command:
ping ftp-server-name
You should see output indicating the IP address of the server and the ping
(round trip) time to the server. If you can not ping the server than you have a
network configuration problem, and you should contact you network
administrator.

Check that passive mode works If the FTP link is connecting to the
FTP server, but is unable to open a data connection, make sure that an FTP
client can use passive mode to transfer data with the server.
Passive mode is the preferred transfer mode and the default for the FTP
message link. In passive mode all data transfer connections are initiated by
the client, in this case the message link. In Active mode the server initiates
all data connections. If your FTP server is sitting behind an incorrectly
configured firewall you may not be able to use the default passive transfer
mode. In this situation the firewall blocks socket connections to the FTP
server on ports other than the FTP control port.
Using an FTP user program that allows you to set the transfer mode between
active and passive, set the transfer mode to passive and try to
upload/download a file. If the client you are using cannot transfer the file
without using active mode than you should either reconfigure the firewall
and FTP server to allow passive mode transfers or set the active_mode
message control parameter to YES. Active mode transfers may not work in
all network configurations. For example: if your client is sitting behind an IP
masquerading gateway incoming connections may fail depending on you
gateway software.

448
Chapter 18 SQL Remote Administration

Check permissions and directory structures If the FTP server is


connecting and having problems getting directory listings or manipulating
files; make sure your permissions are set up correctly and the directories that
you need exist.
Log into the FTP server using an FTP program. Change directories to the
location stored in the root_directory parameter. If the directories you need do
not show up, the root_directory control parameter may be wrong or the
directories may not exist.
Test permissions by fetching a file in your message directory and uploading
a file to the consolidated databases directory. If you get errors your FTP
server permissions are set up incorrectly.

The SMTP message system


The Simple Mail Transfer Protocol (SMTP) is used in Internet e-mail
products.
With the SMTP system, SQL Remote sends messages using Internet mail.
The messages are encoded to a text format and sent in an e-mail message to
the target database. The messages are sent using an SMTP server, and
retrieved from a POP server: this is the way that many e-mail programs send
and receive messages.
$ For a list of operating systems for which SMTP is supported, see
"Supported operating systems" on page 677.
SMTP addresses To use SQL Remote and an SMTP message system, each database
and user IDs participating in the setup requires a SMTP address, and a POP3 user ID and
password. These are distinct identifiers: the SMTP address is the destination
of each message, and the POP3 user ID and password are the name and
password entered by a user when they connect to their mail box.

Separate e-mail account recommended


It is recommended that a separate POP e-mail account be used for SQL
Remote messages.

Troubleshooting If you can not get the SMTP Link to work try connecting to the SMTP/POP3
server from the same machine on which the Message Agent is running using
the same account and password. Use an Internet e-mail program that
supports SMTP/POP3 and make sure to disable the program once the SMTP
message link is working.

449
Using message types

Before the Message Agent connects to the message system to send or receive
SMTP message messages, the user must either have a set of control parameters already set on
control parameters their machine, or must fill in a window with the needed information. This
information is needed only on the first connection. It is saved and used as the
default entries on subsequent connects.
The SMTP message system uses the following control parameters:
♦ local_host This is the name of the local computer. It is useful on
machines where SQL Remote is unable to determine the local host
name. The local host name is needed to initiate a session with any SMTP
server. In most network environments, the local host name can be
determined automatically and this entry is not needed.
♦ TOP_supported SQL Remote uses a POP3 command called TOP
when enumerating incoming messages. The TOP command may not be
supported by all POP servers. Setting this entry to NO will use the
RETR command, which is less efficient but will work with all POP
servers. The default is YES.
♦ smtp_host This is the name of the computer on which the SMTP
server is running. It corresponds to the SMTP host field in the
SMTP/POP3 login dialog.
♦ pop3_host This is the name of the computer on which the POP host is
running. It is commonly the same as the SMTP host. It corresponds to
the POP3 host field in the SMTP/POP3 login dialog.
♦ pop3_userid This is used to retrieve mail. The POP user ID
corresponds to the user ID field in the SMTP/POP3 login dialog. You
must obtain a user ID from your POP host administrator.
♦ pop3_password This is used to retrieve mail. It corresponds to the
password field in the SMTP/POP3 login dialog. If all of these five fields
are set, the login dialog is not displayed.
♦ Debug When set to YES, displays all SMTP and POP3 commands and
responses. This is useful for troubleshooting SMTP/POP support
problems. Default is NO.
The SMTP section of the sqlany.ini file (Windows 3.x) has the following
entries:
[SMTP]
smtp_host=smtp_host
pop3_host=pop3_host
pop3_userid=userid
pop3_password=password
Debug={ yes | no }

450
Chapter 18 SQL Remote Administration

Sharing SMTP/POP addresses


The database should have its own e-mail account for SQL Remote messages,
separate from personal e-mail messages intended for reading. This is because
many e-mail readers will collect e-mail in the following manner:
1 Connect to the POP Host and download all messages.
2 Delete all messages from POP Host
3 Disconnect from POP Host.
4 Read mail from the local file or from memory
This causes a problem, as the e-mail program downloads and deletes all of
the SQL Remote e-mail messages as well as personal messages. If you are
certain that your e-mail program will not delete unread messages from the
POP Host then you may share an e-mail address with the database as long as
you take care not to delete or alter the database messages.
These messages are easy to recognize, as they are filled with lines of
seemingly random text.

The MAPI message system


The Message Application Programming Interface (MAPI) is used in several
popular e-mail systems, such as Microsoft Mail and later versions of Lotus
cc:Mail. SQL Remote supports the MAPI message system under Windows
3.x, Windows 95/98, and Windows NT.
$ For a list of operating systems for which MAPI is supported, see
"Supported operating systems" on page 677.
MAPI addresses To use SQL Remote and a MAPI message system, each database
and user IDs participating in the setup requires a MAPI user ID and address. These are
distinct identifiers: the MAPI address is the destination of each message, and
the MAPI user ID is the name entered by a user when they connect to their
mail box.
MAPI message Although SQL Remote messages may arrive in the same mail box as e-mail
and the e-mail intended for reading, they do not in general show up in your e-mail inbox.
inbox
SQL Remote sends application-defined messages, which MAPI identifies
and hides when the mailbox is opened. In this way, users can use the same e-
mail address and same connection to receive their personal e-mail and their
database updates, yet the SQL Remote messages do not interfere with the
mail intended for reading.
If a message is routed via the Internet, the special message type information
is lost. The message then does show up in the recipient’s mailbox.

451
Using message types

The MAPI message system uses the following control parameters:


MAPI message ♦ Debug When set to YES, displays all MAPI calls and the return codes.
control parameters This is useful for troubleshooting MAPI support problems. Default is
NO.
♦ Force_Download (default YES) controls if the
MAPI_FORCE_DOWNLOAD flag is set when calling MapiLogon.
This might be useful when using remote mail software that dials when
this flag is set.
♦ IPM_Receive This can be set to YES or NO (default NO). If set to
YES, the MAPI link receives IPM messages, which are visible in the
mailbox. If set to NO, the MAPI link receives IPC messages, which are
not visible in the mailbox. This may be useful if your MAPI provider
does not support IPC messages. Also, it may be useful when receiving
messages over the Internet. In this case, the sender might not be using
MAPI or the IPC attributes are have been lost.
♦ IPM_Send This can be set to YES or NO (default NO). If set to YES,
the MAPI link sends IPM messages, which are visible in the mailbox. If
set to NO, the MAPI link sends IPC messages, which are not visible in
the mailbox. This may be useful if your MAPI provider does not support
IPC messages.
♦ Profile Use the specified Microsoft Exchange profile. You should use
this if you are running the Message Agent as a service.
The MAPI section of the sqlany.ini file (Windows 3.x) has the following
entries:
[ MAPI ]
IPM_Send={yes |no }
IPM_Receive={ yes |no }
Force_Download={yes |no }
Debug={yes | no}

The VIM message system


The Vendor Independent Messaging system (VIM) is used in Lotus Notes
and in some releases of Lotus cc:Mail.
To use SQL Remote and a VIM message system, each database participating
in the setup requires a VIM user ID and address. These are distinct
identifiers: the VIM address is the destination of each message, and the VIM
user ID is the name entered by a user when they connect to their mail box.
$ For a list of operating systems for which VIM is supported, see
"Supported operating systems" on page 677.

452
Chapter 18 SQL Remote Administration

The VIM message system uses the following control parameters:


VIM message
control parameters ♦ Path This corresponds to the Path field in the cc:Mail login dialog. It
is not applicable to and is ignored under Lotus Notes.
♦ Userid This corresponds to the User ID field in the cc:Mail login
dialog.
♦ Password This corresponds to the Password field in the cc:Mail login
dialog. If all of Path, Userid, and Password are set, the login dialog is
not displayed.
♦ Debug When set to YES, displays all VIM calls and the return codes.
This is useful for troubleshooting VIM support problems. Default is NO.
♦ Receive_All When set to YES, the Message Agent checks all
messages to see if they are SQL Remote messages. When set to NO (the
defaut), the Message Agent looks only for messages of the application-
defined type SQLRemoteData. This leads to improved performance in
Notes.
Setting ReceiveAll to YES is useful in setups where the message type is
lost, reset, or never set. This includes setups including cc:Mail messages,
or over the Internet.
♦ Send_VIM_Mail When set to YES, the Message Agent sends messages
compatible with Adaptive Server Anywhere releases before 5.5.01, and
compatible with cc:Mail. If this is set to YES, you should ensure that
Receive_All is set to YES also.
The VIM section of the sqlany.ini file (Windows 3.x) has the following
entries:
[ VIM ]
Path=path
Userid=userid
Password=password
Debug={yes | no}
Receive_All = {yes | no}
Send_VIM_Mail = {yes | no}

453
Running the Message Agent

Running the Message Agent


The SQL Remote Message Agent is a key component in SQL Remote
replication. The Message Agent handles both the sending and receiving of
messages. It carries out the following functions:
♦ It processes incoming messages, and applies them in the proper order to
the database.
♦ It scans the transaction log or stable queue at each publisher database,
and translates the log entries into messages for subscribers.
♦ It parcels the log entries up into messages no larger than a fixed
maximum size (50,000 bytes by default), and sends them to subscribers.
♦ It maintains the message tracking information in the system tables, and
manages the guaranteed transmission mechanism.

Executable names On Windows operating systems, the Message Agent for Adaptive Server
Enterprise is named ssremote.exe, and the Message Agent for Adaptive
Server Anywhere is named dbremote.exe. On UNIX operating systems, the
names are ssremote and dbremote, respectively.
$ The Message Agent for Adaptive Server Enterprise uses a stable queue
to hold transactions until they are no longer needed. For more information on
the stable queue, see "How the Message Agent for Adaptive Server
Enterprise works" on page 494.

Message Agent batch and continuous modes


The Message Agent can be run in one of two modes:
♦ Batch mode In batch mode, the Message Agent starts, receives and
sends all messages that can be received and sent, and then shuts down.
Batch mode is useful at occasionally-connected remote sites, where
messages can only be exchanged with the consolidated database when
the connection is made: for example, when the remote site dials up to the
main network.
♦ Continuous mode In continuous mode, the Message Agent
periodically sends messages, at times specified in the properties of each
remote user. When it is not sending messages, it receives messages as
they arrive.
Continuous mode is useful at consolidated sites, where messages may be
coming in and going out at any time, to spread out the workload and to
ensure prompt replication.

454
Chapter 18 SQL Remote Administration

The options available depend on the send frequency options selected for the
remote users. Sending frequency options are described in "Selecting a send
frequency" on page 436.

v To run the Message Agent in continuous mode:


1 Ensure that every user has a sending frequency specified. The sending
frequency is specified by a SEND AT or SEND EVERY option in the
GRANT REMOTE statement (Adaptive Server Anywhere) or
sp_grant_remote procedure (Adaptive Server Enterprise).
2 Start the Message Agent without using the -b command-line switch.

v To run the Message Agent in batch mode:


♦ Either:
♦ Have at least one remote user who has neither a SEND AT nor a
SEND EVERY option in their remote properties, or
♦ Start the Message Agent using the -b command-line switch.

Connections used by the Message Agent


The Message Agent uses a number of connections to the database server.
These are:
♦ One global connection, alive all the time the Message Agent is running.
♦ One connection for scanning the log. This connection is alive during the
scan phase only.
♦ One connection for executing commands from the log-scanning thread.
This connection is alive during the scan phase only.
♦ One connection for the stable queue (Adaptive Server Enterprise only).
This connection is alive during the scan and send phases.
♦ One connection for processing synchronize subscription requests. This
connection is alive during the send phase only.
♦ One connection for each worker thread. These connections are alive
during the receive phase only.

455
Running the Message Agent

Replication system recovery procedures


SQL Remote replication places new requirements on data recovery practices
at consolidated database sites. Standard backup and recovery procedures
enable recovery of data from system or media failure. In a replication
installation, even if such recovery is achieved, the recovered database can be
out of synch with remote databases. This can require a complete
resynchronization of remote databases, which can be a formidable task if the
installation involves large numbers of databases.
In short, recovery of the consolidated database from a failure at the
consolidated site is only part of the task of recovering the entire replication
installation.
Protection of the replication system against media failures has two aspects:
♦ Backup and log management Solid backup procedures and log
management procedures for the consolidated database server are an
essential part of recovery plans. Backup procedures protect against
media failure on the database device. Using a transaction log mirror
protects against media failure on the transaction log device.
$ For more information about backup and log management
procedures, see the sections "Transaction log and backup management"
on page 478 and "Adaptive Server Enterprise transaction log and backup
management" on page 503.
♦ Message Agent configuration The Message Agent command-line
options provide ways for you to tune Message Agent behavior to match
your backup and recovery requirements.
Message Agent configuration is discussed in the following pages.

Replicating only By default, the Message Agent processes all committed transactions. When
backed-up the Message Agent is run with the -u command-line switch, only
transactions transactions that have been backed up by the database backup commands are
processed.
For Adaptive Server Anywhere, transaction log backup is carried out using
Sybase Central or the dbbackup command-line utility, or off-line copying
and renaming of the log file. For Adaptive Server Enterprise, transaction log
backup is carried out using the dump transaction statement.
By sending only backed-up transactions, the replication installation is
protected against media failure on the transaction log. Maintaining a
mirrored transaction log also accomplishes this goal.
The -u switch provides additional protection against total site failure, if
backups are carried out to another site.

456
Chapter 18 SQL Remote Administration

Ensuring consistent Message Agent settings


Some Message Agent settings need to be the same throughout an installation,
and so should be set before deployment. This section lists the settings that
need to be the same.
♦ Maximum message length The maximum message length for SQL
Remote messages has a default value of 50K. This is configurable, using
the Message Agent -l command-line switch. However, the maximum
message length must be the same for each Message Agent in the
installation, and may be restricted by operating system memory
allocation limits.
Received messages that are longer than the limit are deleted as corrupt
messages.
$ For details of this setting, see "The Message Agent" on page 522.

The Message Agent and replication security


Messages sent by the SQL Remote Message Agent have a very simple
encryption that protects against casual snooping. However, the encryption
scheme is not intended to provide full protection against determined efforts
to decipher them.

457
Tuning Message Agent performance

Tuning Message Agent performance

Who needs to read this section? If performance is not a problem at


your site, you do not need to read this section.

There are several options you can use to tune the performance of the
Message Agent. This section describes those options.
Sending messages and receiving messages are two separate processes. The
major performance issues for these two processes are different.
♦ Replication throughput The major bottleneck for total throughput of
SQL Remote sites is generally receiving messages from many remote
databases and applying them to the database at the consolidated site.
You can control this step by tuning the receive process of the Message
Agent at the consolidated site.
♦ Replication turnaround The time lag from when data is entered at
one site to when it appears at other sites is the turnaround time for
replication. You can control this time lag.

Tuning throughput by controlling Message Agent threading


It is assumed in this section that you are tuning the performance of a
Message Agent that is running in continuous mode at a consolidated site.
Worker threads can be used by the Message Agent to apply incoming
messages from remote users. This can improve throughput by allowing
messages to be applied in parallel rather than serially.
Setting the number The number of worker threads is set on the Message Agent command line,
of worker threads using the -w switch. The following command line starts the Message Agent
for Adaptive Server Enterprise with twenty worker threads applying
messages:
ssremote -c "eng=..." -w 20
The default is to use no worker threads, so that all messages are applied
serially. The maximum number of worker threads is 50.
Performance For the Message Agent for Adaptive Server Anywhere, the performance
benefits from advantage will be most significant when the server is on a system with a
worker threads striped drive array.
For Adaptive Server Enterprise, the Message Agent will benefit even more if
the Server is used with multiple engines configured.

458
Chapter 18 SQL Remote Administration

What messages When worker threads are being used, messages from different remote users
are applied in are applied in parallel. Messages from a single remote user are applied
parallel serially. For example, ten messages from a single remote user will be applied
by a single worker thread in the correct order.
Deadlock is handled by re-applying the rolled back transaction at a later
time.
Reading messages from the message system is single-threaded. Messages are
read and the header information is examined (to determine the remote user
and the correct order of application) before passing them off to worker
threads to be applied.
Building messages and sending messages is single-threaded.
Open Client To use multiple worker threads with the Adaptive Server Enterprise Message
version Agent, you need to be using Open Client version 11.1 or above.
The Message Agent prints a message and then does not use worker threads
when pre-11.1 versions are being used. The Open Client version is displayed
in the first few lines of the Message Agent output.

Tuning throughput by caching messages


The Message Agent caches incoming messages in a configurable area of
memory as it reads them.
Specifying the The size of the message cache is specified on the Message Agent command
message cache line, using the -m command-line switch.
size
The -m option specifies the maximum amount of memory to be used by the
Message Agent for building messages. The allowed size can be specified as n
(in bytes), nK, or nM. The default is 2048K (2M).
Example The following command line starts an Adaptive Server Anywhere Message
Agent using twelve Megabytes of memory as a message cache:
dbremote -c "eng=..." -m 12M

How messages are When transactions are large, or messages arrive out of order, they are stored
cached in memory by the Message Agent until the message is to be applied. This
caching of messages prevents rereading of out-of-order messages from the
message system , which may lower performance on large installations. It is
especially important when messages are being read over a WAN (such as
Remote Access Services or POP3 through a modem). It also avoids
contention between worker threads reading messages (a single threaded task)
because the message contents are cached.

459
Tuning Message Agent performance

When the memory usage specified using the -m switch is exceeded,


messages are flushed in a least-recently-used fashion.
This switch is provided primarily for customers considering a single
consolidated database for thousands of remote databases.

Tuning incoming message polling


When running a Message Agent in continuous mode, typically at a
consolidated database site, you can control how often it polls for incoming
messages, and how "patient" it is in waiting for messages that arrive out of
order before requesting that the message be resent. Tuning these aspects of
the behavior can have a significant effect on performance in some
circumstances.
Issues to consider The issues to consider when tuning the message-receiving process are similar
to those when tuning the message-sending process.
♦ Regular messages Your choices dictate how often the Message
Agent polls for incoming messages from remote databases.
♦ Resend requests You can control how many polls to wait until an
out-of-order message arrives, before requesting that it be resent.
♦ Processing incoming messages If your polling period for incoming
messages is too long, compared to the frequency with which messages
are arriving, you could end up with messages sitting in the queue,
waiting to be processed. If your polling period is too short, you will
waster resources polling when no messages are in the queue.
$ For more information on the message sending process, see "Tuning the
message sending process" on page 462.

Polling interval
By default, a Message Agent running in continuous mode polls one minute
after finishing the previous poll, to see whether new messages have arrived.
You can configure the polling interval using the -rd command-line option.
The default polling interval from the end of one poll to the start of another is
one minute. You can poll more frequently using a value in seconds, as in the
following command line:
dbremote -rd 30s
Alternatively, you can poll less frequently, as in the following command line,
which polls every five minutes:
dbremote -rd 5

460
Chapter 18 SQL Remote Administration

Setting a very small interval may have some detrimental impact on overall
system throughput, for the following reasons:
♦ Each poll of the mail server (if you are using e-mail) places a load on
your message system. Too-frequent polling may affect your message
system and produce no benefits.
♦ If you do not modify the Message Agent patience before it assumes that
an out of sequence message is lost, and requests it be sent again, you can
flood your system with resend requests.
In general, you should not use a very small polling interval unless you have a
specific reason for requiring a very quick response time for messages.
Setting larger intervals may provide a better overall throughput of messages
in your system, at the cost of waiting somewhat longer for each message to
be applied. In many SQL Remote installations, optimizing turnaround time is
not the primary concern.

Requesting resends
If, when the Message Agent polls for incoming messages, one message is
missing from a sequence, the Message Agent does not immediately request
that the message be resent. Instead, it has a default patience of one poll.
If the next message expected is number 6 and message 7 is found, the
Message Agent takes no action until the next poll. Then, if no new message
for that user is found, it issues a resend request.
You can change the number of polls for which the Message Agent waits
before sending a request using the -rp command-line option. This option is
often used in conjunction with the -rd option that sets the polling interval.
For example, if you have a very small polling interval, and a message system
that does not preserver the order in which messages arrive, it may be very
common for out-of-sync messages to arrive only after two or three polls have
been completed. In such a case, you should instruct the Message Agent to be
more patient before sending a resend request, by increasing the -rp value. If
you do not do this, a large number of unnecessary resend requests may be
sent.

Example
Suppose there are two remote users, named user1 and user2, and suppose
the Message Agent command line is as follows:
dbremote -rd 30s -rp 3

461
Tuning Message Agent performance

In the following sequence of operations, messages are marked as userX.n so


that user1.5 is the sixth message from user1. The Message Agent expects
messages to start at number 1 for both users.
At time 0 seconds:
1 The Message Agent reads user1.1, user2.4
2 The Message Agent applies user1.1
3 The Message Agent patience is now user1: N/A, user2: 3, as an out of
sequence message has arrived from user 2.
At time 30 seconds:
1 The Message Agent reads: no new messages
2 The Message Agent applies: none
3 The Message Agent patience is now user1: N/A, user2: 2
At time 60 seconds:
1 The Message Agent reads: user1.3
2 The Message Agent applies: no new messages
3 The Message Agent patience: user1: 3, user2: 1
At time 90 seconds:
1 The Message Agent reads: user1.4
2 The Message Agent applies: none
3 The Message Agent patience user1: 3, user2: 0
4 The Message Agent issues resend to user2.
When a user receives a new message, it resets the Message Agent patience
even if that message is not the one expected.

Tuning the message sending process


The turnaround time for replication is governed by how often each sites
sends messages and how often each site polls for incoming messages. To
achieve a small time lag between data entry and data replication, you can set
a small value for the -sd Message Agent command-line option, which
controls the frequency for polling to see if more data needs to be sent.
Issues to consider The issues to consider when tuning the message-sending process are similar
to those when tuning the incoming-message polling frequency:

462
Chapter 18 SQL Remote Administration

♦ Regular messages Your choices dictate how often updates are sent to
remote databases.
♦ Resend requests When a remote user requests that a message be
resent, the Message Agent needs to take special action that can interrupt
regular message sending. You can control the urgency with which these
resend requests are processed.
♦ Number and size of messages If you send messages very frequently,
there is more chance of small messages being sent. Sending messages
less frequently allows more instructions to be grouped in a single
message. If a large number of small messages is a concern for your
message system, then you may have to avoid using very small polling
periods.
$ For more information on tuning polling for the incoming-messages, see
"Tuning incoming message polling" on page 460.

Polling interval
You control the interval to wait between polls for more data from the
transaction log to send using the -sd command-line option, which has a
default of one minute. The following example sets the polling interval to 30
seconds:
dbremote -sd 30s ...
Alternatively, you can poll less frequently, as in the following command line,
which polls every five minutes:
dbremote -sd 5
Setting a very small interval may have some detrimental impact on overall
system throughput, for the following reasons:
♦ Too-frequent polling produces many short messages. If the message load
places a strain on your message system, throughput could be affected.
Setting larger intervals may provide a better overall throughput of messages
in your system, at the cost of waiting somewhat longer for each message to
be applied. In many SQL Remote installations, optimizing turnaround time is
not the primary concern.

463
Tuning Message Agent performance

Resending messages
When a user requests that a message be resent, the message has to be
retrieved from early in the transaction log. Going back in the transaction log
to retrieve this message and send it causes the Message Agent to interrupt the
regular sending process. If you are tuning your SQL Remote installation for
optimum performance, you must balance the urgency of sending requests for
resent messages with the priority of processing regular messages.
The -ru command-line option controls the urgency of the resend requests.
The value for the parameter is a time in minutes (or in other units if you add
s or h to the end of the number), with a default of zero.
To help the Message Agent delay processing resend requests until more
have arrived before interrupting the regular message sending activity, set this
option to a longer time.
The following command line waits one hour until processing a resend
request.
dbremote -ru 1h ...

If you do not specify the -ru option, then a default value is picked by the
Message Agent, based on the send interval of the users that have requested
that data be resent. The elapsed time between receiving a resend request for a
user and rescanning the log does not exceed half of the send interval for that
user.

464
Chapter 18 SQL Remote Administration

Encoding and compressing messages


As messages pass through e-mail and other message systems, there is a
danger of them becoming corrupted. For example, some message systems
use certain characters or character combinations as control characters.
Message size affects the efficiency with which messages pass through a
system. Compressed messages can be processed more efficiently by a
message system than uncompressed messages. On the other hand, carrying
out compression can itself take a significant amount of time.
SQL Remote SQL Remote has a message encoding and compression scheme built in to the
encoding and Message Agent. The scheme provides the following features:
compression
♦ Compatibility The system can be set up to be compatible with
previous versions of the software.
♦ Compression You can select a level of compression for your
messages.
♦ Encoding SQL Remote encodes messages to ensure that they pass
through message systems uncorrupted. The encoding scheme can be
customized to provide extra features.

Settings for To be compatible with previous versions of the software, you should set the
compatibility database option COMPRESSION to be -1 (minus one) at each database
running the Version 6 software. This setting ensures that messages are sent
out in a format compatible with older versions of the software.
Upgrading SQL If you upgrade the consolidated database Message Agent first, you should set
Remote its COMPRESSION database option to -1. As each remote site in your
replication system is upgraded to Version 6, you can change its setting of the
COMPRESSION option to a value between 0 (no compression) and 9
(maximum compression). This allows you to take advantage of compression
features on messages being sent to the consolidated database. Once all
remote sites are upgraded, you can set the consolidated site Message Agent
COMPRESSION option to a value other than -1.
In addition, setting COMPRESSION to a value other than -1 allows you to
take advantage of the Version 6 message encoding improvements.

The encoding scheme


The default message-encoding behavior of SQL Remote is as follows:
♦ For message systems that can use binary message formats, no encoding
is carried out.

465
Encoding and compressing messages

♦ Some message systems, including SMTP, VIM, and MAPI, require text-
based message formats. For these systems, an encoding DLL
(dbencod.dll for Adaptive Server Anywhere and ssencod.dll for
Adaptive Server Enterprise) translates messages into a text format
before sending. The message format is unencoded at the receiving end
using the same DLL.
♦ You can instruct SQL Remote to use a custom encoding scheme. The
tools for building a custom encoding scheme are described in the
following section.
♦ If the COMPRESSION database option is set to -1, then a Version 5
compatible encoding is carried out for all message systems.

Creating custom encoding schemes


You can implement a custom encoding scheme by building a custom
encoding DLL. You could use this DLL to apply special features required for
a particular messages system, or to collect statistics, such as how many
messages or how many bytes were sent to each user.
The header file dbrmt.h, installed into the h subdirectory of your installation
directory, provides an application programming interface for building such a
scheme.
To instruct SQL Remote to use your DLL for a particular message system,
you must make a registry entry for that system. The registry entry should be
made in the following location:
Software
\Sybase
\SQL Remote
\message-system
\encode_dll
where message-system is one of the SQL Remote message systems (file,
smtp, and so on). You should set this registry entry to the name of your
encoding DLL.

Encoding and decoding must be compatible


If you implement a custom encoding, you must make sure that the DLL is
present at the receiving end, and that the DLL is in place to decode your
messages properly.

466
Chapter 18 SQL Remote Administration

The message tracking system


SQL Remote has a message tracking system to ensure that all replicated
operations are applied in the correct order, no operations are missed, and no
operation is applied twice.
Message system failures may lead to replication messages not reaching their
destination, or reaching it in a corrupt state. Also, messages may arrive at
their destination in a different order from that in which they were sent. This
section describes the SQL Remote system for detecting and correcting
message system errors, and for ensuring correct application of messages.
If you are using an e-mail message system, you should confirm that e-mail is
working properly between the two machines if SQL Remote messages are
not being sent and received properly.
The SQL Remote message tracking system is based on status information
maintained in the remoteuser SQL Remote system table. The table is
maintained by the Message Agent. The Message Agent at a subscriber
database sends confirmation to the publisher database to ensure that
remoteuser is maintained properly at each end of the subscription.
For Adaptive Server Anywhere, the remoteuser table is the
sys.sysremoteuser system table. For Adaptive Server Enterprise, this is the
sr_remoteuser table.

Status information in the remoteuser table


The remoteuser SQL Remote system table contains a row for each
subscriber, with status information for messages sent to and received by that
subscriber. At the consolidated database, remoteuser contains a row for each
remote user. At each remote database, remoteuser contains a single row
maintaining information for the consolidated database. (Recall that the
consolidated database subscribes to publications from the remote database.)
The remoteuser SQL Remote system table at each end of a subscription is
maintained by the Message Agent.

Tracking messages by transaction log offsets


The message-tracking status information takes the form of offsets in the
transaction logs of the publisher and subscriber databases. Each COMMIT is
marked in the transaction log by a well-defined offset. The order of
transactions can be determined by comparing their offset values.

467
The message tracking system

Message ordering When messages are sent, they are ordered by the offset of the last COMMIT
of the preceding message. If a transaction spans several messages, there is a
serial number within the transaction to order the messages correctly. The
default maximum message size is 50,000 bytes, but you can use the Message
Agent -l command-line switch to change this setting.
Sending messages The log_sent column holds the local transaction log offset for the latest
message sent to the subscriber. When the Message Agent sends a message, it
sets the log_sent value to the offset of the last COMMIT in the message.
Once the message has been received and applied at the subscribed database,
confirmation is sent back to the publisher. When the publisher Message
Agent receives the confirmation, it sets the confirm_sent column for that
subscriber with the local transaction log offset. Both log_sent and
confirm_sent are offsets in the local database transaction log, and
confirm_sent cannot be a later offset than log_sent.
Receiving When the Message Agent at a subscriber database receives and applies a
messages replication update, it updates the log_received column with the offset of the
last COMMIT in the message. The log_received column at any subscriber
database therefore contains a transaction log offset in the publisher database’s
transaction log. After the operations have been received and applied, the
Message Agent sends confirmation back to the publisher database and also
sets the confirm_received value in the local SYSREMOTEUSER table. The
confirm_received column at any subscriber database contains a transaction
log offset in the publisher database’s transaction log.
Subscriptions are SQL Remote subscriptions are two-way operations: each remote database is
two-way a subscriber to publications of the consolidated database and the consolidated
database subscribes to a matching publication from each remote database.
Therefore, the remoteuser SQL Remote system tables at the consolidated
and remote database hold complementary information.
The Message Agent applies transactions and updates the log_received value
atomically. If a message contains several transactions, and a failure occurs
while a message is being applied, the log_received value corresponds
exactly to what has been applied and committed.
Resending The remoteuser SQL Remote table contains two other columns that handle
messages resending messages. The resend_count and rereceive_count columns are
retry counts that are incremented when messages get lost or deleted for some
reason.
In general, the log_send column has the same value as the log_sent column.
However, if the log_send has a value that is greater than log_sent, the
Message Agent sends messages to the subscriber immediately on its next
run.

468
Chapter 18 SQL Remote Administration

Handling of lost or corrupt messages


When messages are received at a subscriber database, the Message Agent
applies them in the correct order (determined from the log offsets) and sends
confirmation to the publisher. If a message is missing, the Message Agent
increments the local value of rereceive_count, and requests that it be resent.
Other messages present or en route are not applied.
The request from a subscriber to resend a message increments the
resend_count value at the publisher database, and also sets the publisher’s
log_sent value to the value of confirm_sent. This resetting of the log_sent
value causes operations to be resent.

Users cannot reset log_sent


The log_sent value cannot be reset by a user, as it is in a system table.

Message Each message is identified by three values:


identification
♦ Its resend_count.
♦ The transaction log offset of the last COMMIT in the previous message.
♦ A serial number within transactions, for transactions that span messages.
Messages with a resend_count value smaller than rereceive_count are not
applied; they are deleted. This ensures that operations are not applied more
than once.

469
The message tracking system

470
C H A P T E R 1 9

Administering SQL Remote for Adaptive


Server Anywhere

About this chapter This chapter details set-up, and management issues for SQL Remote
administrators using Adaptive Server Anywhere as a consolidated database.

Contents
Topic Page
Running the Message Agent 472
Error reporting and handling 474
Transaction log and backup management 478
Using passthrough mode 489

471
Running the Message Agent

Running the Message Agent


This section describes how to run the Message Agent for Adaptive Server
Anywhere.
$ For information on features of the Message Agent that are common to
Adaptive Server Anywhere and Adaptive Server Enterprise, see "SQL
Remote Administration" on page 429.

Starting the Message Agent


The Message Agent has a set of command-line switches that control its
behavior. The only command-line switch that is required for the Message
Agent to run is the connection parameters switch (-c).
$ For more information on connection parameters, see "Connection
parameters" on page 60 of the book ASA User’s Guide.

Verbose keyword Short form Argument


DatabaseFile DBF string
DatabaseName DBN string
DatabaseSwitches DBS string
EngineName ENG string
Password PWD string
Start Start string
Userid UID string

Running the Message Agent as a service


If you are running the Message Agent in continuous mode (not batch mode),
on Windows NT or Windows 95, you may wish to keep the Message Agent
running all the time that the server is running.
You can do this by running the Message Agent as a service under Windows
NT or Windows 95. A service for Windows NT can be configured to keep
running even when the current user logs out, and to start as soon as the
operating system is started.
$ For a full description of running programs as services, see "Running the
Database Server" on page 3 of the book ASA User’s Guide.

472
CHAPTER 19 Administering SQL Remote for Adaptive Server Anywhere

The Message Agent and replication security


In the tutorials in the previous chapter, the Message Agent was run using a
user ID with DBA permissions. The operations in the messages are carried
out from the user ID specified in the Message Agent connection string; by
using the user ID DBA, you can be sure that the user has permissions to make
all the changes.
In many situations, distributing the DBA user ID and password to all remote
database users is an unacceptable practice for security and data privacy
reasons. SQL Remote provides a solution that enables the Message Agent to
have full access to the database in order to make any changes contained in
the messages without creating security problems.
A special permission, REMOTE DBA, has the following properties:
♦ No distinct permissions when not connected from the Message
Agent A user ID granted REMOTE DBA authority has no extra
privileges on any connection apart from the Message Agent. Therefore,
even if the user ID and password for a REMOTE DBA user is widely
distributed, there is no security problem. As long as the user ID has no
permissions beyond CONNECT granted on the database, no one can use
this user ID to access data in the database.
♦ Full DBA permissions from the Message Agent When connecting
from the Message Agent, a user ID with REMOTE DBA authority has
full DBA permissions on the database.

Using REMOTE A suggested practice is to grant REMOTE DBA authority at the consolidated
DBA permission database to the publisher and to each remote user. When the remote database
is extracted, the remote user becomes the publisher of the remote database,
and is granted the same permissions they were granted on the consolidated
database, including the REMOTE DBA authority which enables them to use
this user ID in the Message Agent connection string. Adopting this procedure
means that there are no extra user IDs to administer, and each remote user
needs to know only one user ID to connect to the database, whether from the
Message Agent (which then has full DBA authority) or from any other client
application (in which case the REMOTE DBA authority grants them no extra
permissions).
Granting REMOTE You can grant REMOTE DBA permissions to a user ID named dbremote as
DBA permission follows:
GRANT REMOTE DBA
TO dbremote
IDENTIFIED BY dbremote
In Adaptive Server Anywhere, you can add the REMOTE DBA authority to
a remote user by checking the appropriate option in the New Remote User
Wizard.

473
Error reporting and handling

Error reporting and handling


This section describes how errors are reported and handled by the Message
Agent.

Default error handling


The default action taken by the Message Agent when an error occurs is to
record the fact in its log output. The Message Agent sends log output to a
window or a log file recording its operation. By default, log output is sent to
the window only; the -o command-line option sends output to a log file as
well.
The Message Agent may print more information in the output log than in the
window. The Message Agent log includes the following:
♦ Listing of messages applied.
♦ Listing of failed SQL statements.
♦ Listing of other errors.

UPDATE conflicts UPDATE conflicts are not errors, and so are not reported in the Message
are not errors Agent output.
$ For more information on the log file, see "The Message Agent" on
page 522.

Ignoring errors
There may be exceptional cases where you wish to allow an error
encountered by the Message Agent when applying SQL statements to go
unreported. This may arise when you know the conditions under which the
error occurs and are sure that it does not produce inconsistent data and that
its consequences can safely be ignored.
To allow errors to go unreported, you can create a BEFORE trigger on the
action that causes the known error. The trigger should signal the
REMOTE_STATEMENT_FAILED SQLSTATE (5RW09) or SQLCODE (-
288) value.
For example, if you wish to quietly fail INSERT statements on a table that
fail because of a missing referenced column, you could create a BEFORE
INSERT trigger that signals the REMOTE_STATEMENT_FAILED
SQLSTATE when the referenced column does not exist. The INSERT
statement fails, but the failure is not reported in the Message Agent log.

474
CHAPTER 19 Administering SQL Remote for Adaptive Server Anywhere

Implementing error handling procedures


SQL Remote allows you to carry out some other process in addition to
logging a message if an error occurs. The Replication_error database option
allows you to specify a stored procedure to be called by the Message Agent
when an error occurs. By default no procedure is called.
The procedure must have a single argument of type CHAR, VARCHAR, or
LONG VARCHAR. The procedure is called twice: once with the error
message and once with the SQL statement that causes the error.
While the option allows you to track and monitor errors in replication, you
must still design them out of your setup: this option is not intended to resolve
such errors.
For example, the procedure could insert the errors into a table with the
current time and remote user ID, and this information can then replicate back
to the consolidated database. An application at the consolidated database can
create a report or send e-mail to an administrator when errors show up.
$ For information on setting the REPLICATION_ERROR option, see
"SQL Remote options" on page 542.

Example: e-mailing notification of errors


You may wish to receive some notification at the consolidated database
when the Message Agent encounters errors. This section demonstrates a
method to send Email messages to an administrator when an error occurs.
A stored procedure The stored procedure for this example is called sp_LogReplicationError,
and is owned by the user cons. To cause this procedure to be called in the
event of an error, set the Replication_error database option using
Interactive SQL or Sybase Central:
SET OPTION PUBLIC.Replication_error =
’cons.sp_LogReplicationError’
The following stored procedure implements this notification:
CREATE PROCEDURE cons.sp_LogReplicationError
(IN error_text LONG VARCHAR)
BEGIN
DECLARE current_remote_user CHAR(255);
SET current_remote_user = CURRENT REMOTE USER;

// Log the error


INSERT INTO cons.replication_audit
( remoteuser, errormsg)
VALUES
( current_remote_user, error_text);

475
Error reporting and handling

COMMIT WORK;

//Now notify the dba an error has occurred


// using email. We only want this information if //
the error occurred on the consolidated database
// We want the email to contain the error strings //
the Message Agent is passing to the procedure
IF CURRENT PUBLISHER = ’cons’ THEN
CALL sp_notify_dba( error_text );
END IF
END;
The stored procedure calls another stored procedure to manage the sending
of Email:
CREATE PROCEDURE sp_notify_dba(in msg long varchar)
BEGIN
DECLARE rc INTEGER;
rc=call xp_startmail(mail_user=’davidf’);
//If successful logon to mail
IF rc=0 THEN
rc=call xp_sendmail(
recipient=’Doe, John; John, Elton’,
subject=’SQL Remote Error’,
"message"=msg);
//If mail sent successfully, stop
IF rc=0 THEN
call xp_stopmail()
END IF
END IF
END;

An audit table An audit table could be defined as follows:


CREATE TABLE replication_audit (
id INTEGER DEFAULT AUTOINCREMENT,
pub CHAR(30) DEFAULT CURRENT PUBLISHER,
remoteuser CHAR(30),
errormsg LONG VARCHAR,
timestamp DATETIME DEFAULT CURRENT TIMESTAMP,
PRIMARY KEY (id,pub)
);
The columns have the following meaning:

Column Description
pub Current publisher of the database (lets you know at what
database it was inserted)
remoteuser Remote user applying the message (lets you know what database
it came from)
errormsg Error message passed to the Replication_error procedure

476
CHAPTER 19 Administering SQL Remote for Adaptive Server Anywhere

Here is a sample insert into the table from the above error:
INSERT INTO cons.replication_audit
( id,
pub,
remoteuser,
errormsg,
"timestamp")
VALUES
( 1,
’cons’,
’sales’,
’primary key for table ’’reptable’’ is not unique
(-193)’,
’1997/apr/21 16:03:13.836’)
COMMIT WORK
Since Adaptive Server Anywhere supports calling external DLLs from stored
procedures you can also design a paging system, instead of using Email.
An example of an For example, if a row is inserted at the consolidated using the same primary
error key as one inserted at the remote, the Message Agent displays the following
errors:
Received message from "cons" (0-0000000000-0)
SQL statement failed: (-193) primary key for table ’reptable’ is not unique
INSERT INTO cons.reptable(id,text,last_contact)
VALUES (2,’dave’,’1997/apr/21 16:02:38.325’)
COMMIT WORK
The messages that arrived in Doe, John and Elton, John’s email each had a
subject of SQL Remote Error:
primary key for table ’reptable’ is not unique (-193)
INSERT INTO cons.reptable(id,text,last_contact) VALUES
(2,’dave’,’1997/apr/21 16:02:52.605’)

477
Transaction log and backup management

Transaction log and backup management


The importance of Replication depends on access to operations in the transaction log, and
good backup access to old transaction logs is sometimes required. This section describes
practices how to set up backup procedures at the consolidated and remote databases to
ensure proper access to old transaction logs.
It is crucial to have good backup practices at SQL Remote consolidated
database sites. A lost transaction log could easily mean having to re-extract
remote users. At the consolidated database site, a transaction log mirror is
recommended.
$ For information on transaction log mirrors and other backup procedure
information, see the chapter "Backup and Recovery", in the Adaptive Server
Anywhere User’s Guide.
Ensuring access to All transaction logs must be guaranteed available until they are no longer
old transactions needed by the replication system.
In many setups, users of remote databases may receive updates from the
office server every day or so. If some messages get lost or deleted, and have
to be resent by the message-tracking system, it is possible that changes made
several days ago will be required. If a remote user takes a vacation, and
messages have been lost in the meantime, changes weeks old may be
required. If the transaction log is backed up daily, the log with the changes
will no longer be running on the server.

Setting the transaction log directory


When the Message Agent needs to scan transaction logs other than the
current log, it looks through all the transaction log files kept in a designated
transaction log directory. A setting on the Message Agent command line
tells the Message Agent which directory this is.
Example For example, the following command line tells the Message Agent to look in
the directory e:\archive to find old transaction logs. The command must be
entered all on one line.
dbremote -c "eng=server_name;uid=dba;pwd=sql" e:\archive

Log names are not The Message Agent opens all the files in the transaction log directory to
important determine which files are logs, so the actual names of the log files are not
important.
This section describes how you can set up a backup procedure to ensure that
such a directory is kept in proper shape.

478
CHAPTER 19 Administering SQL Remote for Adaptive Server Anywhere

Backup utility options


The Adaptive Server Anywhere backup utility has several options, accessible
through Sybase Central wizard selections or through dbbackup command-
line switches, that control its behavior.
This section describes two approaches to using the backup utility in SQL
Remote consolidated database backups. Backups must ensure that a set of
transaction logs suitable for use by the Message Agent is always available.

Using the live directory as the transaction log directory


It is recommended that you use the option to rename and restart the
transaction log when backing up the consolidated database and remote
database transaction logs. For the dbbackup command-line utility, this is the
-r command-line switch.
The figure below illustrates a database named consol.db, with a transaction
log named consol.log in the same directory. For the sake of simplicity, we
consider the log to be in the same directory as the database, although this
would not be generally safe practice in a production environment. The
directory is named c:\live.

97120100.log
97120101.log
consol.db
consol.log

C:\Live

A backup The following command line backs up the database using the rename and
command line restart option:
dbbackup -r -c "uid=dba;pwd=sql" c:\archive
The connection string options would be different for each database.
Effects of the If you back up the transaction log to a directory c:\archive using the rename
backup and restart option, the Backup utility carries out the following tasks:
1 Backs up the transaction log file, creating a backup file
c:\archive\consol.log.

479
Transaction log and backup management

2 Renames the existing transaction log file to 971201nn.log, where nn is


the lowest available integer, starting at 00.
3 Starts a new transaction log, as consol.log.
After several backups, the live directory contains a set of sequential
transaction logs.

97120100.log
97120101.log
consol.db
97120102.log
consol.log
consol.log
consol.db

C:\Live
C:\Archive

A Message Agent You can run the Message Agent with access to these log files using the
command line following command line:
dbremote -c "dbn=hq;..." c:\live

Using the backup directory as the transaction log directory


An alternative procedure is to use the backup directory as the transaction log
directory.
Again, the figure below illustrates a database named consol.db, with a
transaction log named consol.log in the same directory. For the sake of
simplicity, we consider the log to be in the same directory as the database,
although this would not be generally safe practice in a production
environment. The directory is named c:\live.

480
CHAPTER 19 Administering SQL Remote for Adaptive Server Anywhere

97120100.log
97120101.log
consol.db
consol.log

C:\Live

A backup The following command line backs up the database using the rename and
command line restart option, and also uses an option to rename the transaction log backup
file:
dbbackup -r -k -c "uid=dba;pwd=sql" c:\archive
The connection string options would be different for each database.
Effects of the If you back up the transaction log to a directory c:\archive using the rename
backup and restart option and the log renaming option, the Backup utility carries out
the following tasks:
1 Renames the existing transaction log file to 971201nn.log, where nn is
the lowest available integer, starting at 00.
2 Backs up the transaction log file to the backup directory, creating a
backup file named 971201nn.log
3 Starts a new transaction log, as consol.log.
After several backups, the live directory and also the archive directory
contain a set of sequential transaction logs.

97120100.log 97120100.log
97120101.log 97120101.log
consol.db consol.db
97120102.log 97120102.log
consol.log

C:\Live C:\Archive

481
Transaction log and backup management

A Message Agent You can run the Message Agent with access to these log files using the
command line following command line:
dbremote -c "dbn=hq;..." c:\archive

Old log names different before 5.5.01


Prior to release 5.5.01 of Adaptive Server Anywhere, the old log files
were named consol.l00, consol.l01, and so on. The name change was
introduced to allow more old logs to be stored. As the Message Agent
scans all the files in the specified directory, regardless of their names, the
name change should not affect existing applications.

Managing old transaction logs


All transaction logs must be guaranteed available until they are no longer
needed by the replication system: at that point, they can be discarded.
The replication system no longer needs the logs when all remote databases
have received and successfully applied the messages contained in the log
files. Remote databases confirm the successful receipt of messages from the
consolidated database, and the confirmation sets a value in the consolidated
database SQL Remote tables (see "The message tracking system" on
page 467). The old transaction logs at the consolidated database are no
longer needed by SQL Remote when this receipt confirmation has been
received from all remote databases.
Using the You can use the Delete_old_logs database option at the consolidated
Delete_old_logs database to manage old transaction logs automatically.
option
The DELETE_OLD_LOGS database option is set by default to OFF. If it is
set to ON, then the old transaction logs are deleted automatically by the
Message Agent when they are no longer needed. A log is no longer needed
when all subscribers have confirmed receiving all changes recorded in that
log file.
You can set the DELETE_OLD_LOGS option either for the PUBLIC group
or just for the user contained in the Message Agent connection string.
Example ♦ The following statement sets the public DELETE_OLD_LOGS:
SET OPTION PUBLIC.DELETE_OLD_LOGS = ’ON’

482
CHAPTER 19 Administering SQL Remote for Adaptive Server Anywhere

Recovery from database media failure for consolidated databases


This section describes how to recover from a media failure on the database
device at the consolidated database.
The procedures to follow are easiest to describe if there is only one
transaction log file. While this might not be common for consolidated
databases, it is described first, followed by a more common but complicated
situation with a set of transaction log files.

Recovery with a single transaction log


In this case, we assume that there is a single transaction log file, which has
existed since the database was created. Also, we assume previous backups of
the database file have been made and are available, for example on tape.

v To recover the database:


1 Make a copy of the database and log file.
2 Restore the database (.db) file, not the log file, from tape into a
temporary directory.
3 Start the database using the existing transaction log and the -a
command-line switch, to apply the transactions and bring the database
file up to date.
4 Start the database in your normal way. Any new activity will be
appended to the current transaction log.

483
Transaction log and backup management

X
Media failure
on the
database file

Transaction log Database file


(intact) (corrupt)

Restore
backed up
database file

Transaction log Old database


(intact) file (intact)
Start
database
with
transaction
log
Transaction log Database file
(intact) (restored)

Example This example illustrates recovery using a mirrored transaction log.


Suppose you have a consolidated database file named consol.db in a
directory c:\dbdir, and a transaction log file c:\logdir\consol.log which is
mirrored to d:\mirdir\consol.mlg.

v To recover from media failure on the C drive:


1 Backup the mirrored transaction log d:\mirdir\consol.mlg.
2 Replace the failed hardware and re-install all affected software.
3 Create a temporary directory to perform the recovery in (for example,
c:\recover)
4 Restore the most recent backup of the database file, consol.db, to
c:\recover\consol.db.
5 Copy the mirror transaction log, d:\mirdir\consol.mlg, to the recovery
directory with a .log extension, giving c:\recover\consol.log.
484
CHAPTER 19 Administering SQL Remote for Adaptive Server Anywhere

6 Start the database using the following command line:


dbeng7 -a C:\RECOVER\CONSOL.DB
7 Shutdown the database server.
8 Backup the recovered database and transaction log from c:\recover.
9 Copy the files from c:\recover to the appropriate production directories:
♦ Copy c:\recover\consol.db to c:\dbdir\consol.db
♦ Copy c:\recover\consol.log to c:\dbdir\consol.lOG, and to
d:\mirdir\consol.mlg.
10 Restart your system normally.

Recovery with multiple transaction logs


If you have a set of transaction logs, the procedure is different. We assume
previous backups of the database file have been made and are available, for
example on tape.

v To recover the database:


1 Make a copy of the database and log file.
2 Restore the database (.db) file, not the log file, from tape into a
temporary directory.
3 In the temporary directory, start the database, applying the old logs
using the -a command-line switch, applying the named transaction logs
in the correct order.
4 Start the database using the current transaction log and the -a command-
line switch, to apply the transactions and bring the database file up to
date.
5 Start the database in your normal way. Any new activity will be
appended to the current transaction log.

Example Suppose you have a consolidated database file named c:\dbdir\cons.db. The
transaction log file c:\dbdir\cons.log is mirrored to d:\mirdir\cons.mlg.
Assume that you perform full backups weekly, and you perform incremental
backups daily using the following command:
dbbackup -c "uid=dba;pwd=sql" -r -t E:\BACKDIR

485
Transaction log and backup management

This command backs up the transaction log cons.log to the directory


e:\backdir. The transaction log file is then renamed to dateNN.log, where date
is the current date and NN is the next number in sequence, and a new
transaction log is started. The directory e:\backdir is then backed up using a
third-party utility.
In this scenario you would be running the Message Agent with the optional
directory to point to the renamed transaction log files. The Message Agent
command line would be
dbremote -c "uid=dba;pwd=sql" C:\DBDIR
On the third day following the weekly backup the database file gets
corrupted because of a bad disk block.

v To recover from media failure on the C: drive:


1 Backup the mirrored transaction log d:\mirdir\cons.mlg.
2 Create a temporary directory to perform the recovery in. We will call it
c:\recover.
3 Restore the most recent backup of the database file, cons.db to
c:\recover\cons.db.
4 Apply the renamed transaction logs in order, as follows
dbeng7 -a C:\DBDIR\date00.LOG C:\RECOVER\CONS.DB
dbeng7 -a C:\DBDIR\date01.LOG C:\RECOVER\CONS.DB
5 Copy the current transaction log, c:\dbdir\cons.log to the recovery
directory, giving c:\recover\cons.log.
6 Start the database using the following command:
dbeng7 C:\RECOVER\CONS.DB
7 Shutdown the database server.
8 Backup the recovered database and transaction log from c:\recover.
9 Copy the files from c:\recover to the appropriate production directories.
♦ Copy c:\recover\cons.db to c:\dbdir\cons.db.
♦ Copy c:\recover\cons.log to c:\dbdir\cons.log, and to
d:\mirdir\cons.mlg.
10 Restart your system as normal.

486
CHAPTER 19 Administering SQL Remote for Adaptive Server Anywhere

Backup procedures at remote databases


Backup procedures are not as crucial at remote databases as at the
consolidated database. You may choose to rely on replication to the
consolidated database as a data backup method. In the event of a media
failure, the remote database would have to be re-extracted from the
consolidated database, and any operations that have not been replicated
would be lost. (You could use the log translation utility to attempt to recover
lost operations.)
Even if you do choose to rely on replication to protect remote database data,
backups still need to be done periodically at remote databases to prevent the
transaction log from growing too large. You should use the same option
(rename and restart the log) as at the consolidated database, running the
Message Agent so that it has access to the renamed log files. If you set the
DELETE_OLD_LOGS option to ON at the remote database, the old log files
will be deleted automatically by the Message Agent when they are no longer
needed.
Automatic You can use the -x Message Agent command-line switch to eliminate the
transaction log need to rename the transaction log on the remote computer when the
renaming database server is shut down. The -x option renames transaction log after it
has been scanned for outgoing messages.

Upgrading consolidated databases


This section describes issues in upgrading a consolidated database in a SQL
Remote environment. The same considerations apply to Adaptive Server
Anywhere databases that are primary sites in a Sybase Replication Server
installation.
Installing new software does not always make new features available. In
many cases, new features require the Upgrade utility to be run on databases.
The Upgrade utility adds any information to the system catalog required for
new features to be available. When you run the Upgrade utility, it tells you to
archive the transaction log. The reason for this is that a new transaction log is
created by the Upgrade utility, with a new file format.
When using SQL Remote or Replication Server, the transaction log must be
kept for the Message Agent and the Replication Agent, respectively. After
running the Upgrade utility, you should shut down the engine, rename the
log, and leave it for the Message Agent to delete. The log should also be
archived for backup purposes.
$ For information on the Upgrade utility, see "The Upgrade utility" on
page 133 of the book ASA Reference.

487
Transaction log and backup management

Unloading and reloading a consolidated database


If a database is participating in replication, particular care needs to be taken
if you wish to unload and reload the databases.
Replication is based on the transaction log. When a database is unloaded and
reloaded, the old transaction log is no longer available. For this reason, good
backup practices are especially important when participating in replication.

v To unload and reload a consolidated database:


1 Shut down the existing database.
2 Perform a full off-line backup by copying the database and transaction
log files to a secure location.
3 Run the dbtran utility to display the starting offset and ending offset of
the database’s current transaction log file. Note the ending offset for later
use.
4 Rename the current transaction log file so that it is not modified during
the unload process, and place this file in the off-line directory.
5 Start the existing database.
6 Unload the database.
7 Shut down the existing database. This database and any log file created
in this and the previous step is no longer needed.
8 Initialize a new database.
9 Reload the data into the new database.
10 Shut down the new database.
11 Erase the current transaction log file for the new database.
12 Use dblog on the new database with the ending offset noted in step 3 as
the -z parameter, and also set the relative offset to zero.
dblog -x 0 -z 137829 database-name.db
13 When you run the Message Agent, provide it with the location of the
original off-line directory on its command line.

488
CHAPTER 19 Administering SQL Remote for Adaptive Server Anywhere

Using passthrough mode


The publisher of the consolidated database can directly intervene at remote
sites using a passthrough mode, which enables standard SQL statements to
be passed through to a remote site. By default, passthrough mode statements
are executed at the local (consolidated) database as well, but an optional
keyword prevents the statements from being executed locally.

Caution
Always test your passthrough operations on a test database with a remote
database subscribed. Never run untested passthrough scripts against a
production database.

Starting and Passthrough mode is started and stopped using the PASSTHROUGH
stopping statement. Any statement entered between the starting PASSTHROUGH
passthrough statement and the PASSTHROUGH STOP statement which terminates
passthrough mode is checked for syntax errors, executed at the current
database, and also passed to the identified subscriber and executed at the
subscriber database. We can call the statements between a starting and
stopping passthrough statement a passthrough session.
The following statement starts a passthrough session which passes the
statements to a list of two named subscribers, without being executed at the
local database:
PASSTHROUGH ONLY
FOR userid_1, userid_2;

Directing The following statement starts a passthrough session that passes the
passthrough statements to all subscribers to the specified publication:
statements PASSTHROUGH ONLY
FOR SUBSCRIPTION TO [owner].pubname [ ( string ) ] ;
Passthrough mode is additive. In the following example, statement_1 is sent
to user_1, and statement_2 is sent to both user_1 and user_2.
PASSTHROUGH ONLY FOR user_1 ;
statement_1 ;
PASSTHROUGH ONLY FOR user_2 ;
statement_2 ;
The following statement terminates a passthrough session:
PASSTHROUGH STOP ;
PASSTHROUGH STOP terminates passthrough mode for all remote users.

489
Using passthrough mode

Order of Passthrough statements are replicated in sequence with normal replication


application of messages, in the order in which the statements are recorded in the log.
passthrough
Passthrough is commonly used to send data definition language statements.
statements
In this case, replicated DML statements use the before schema before the
passthrough and the after schema following the passthrough.
Notes on using ♦ You should always test your passthrough operations on a test database
passthrough mode with a remote database subscribed. You should never run untested
passthrough scripts against a production database.
♦ You should always qualify object names with the owner name.
PASSTHROUGH statements are not executed at remote databases from
the same user ID. Consequently, object names without the owner name
qualifier may not be resolved correctly.

Uses and limitations of passthrough mode


Passthrough mode is a powerful tool, and should be used with care. Some
statements, especially data definition statements, could cause a running SQL
Remote setup to come tumbling down. SQL Remote relies on each database
in a setup having the same objects: if a table is altered at some sites but not at
others, attempts to replicate data changes will fail.
Also, it is important to remember that in the default setting passthrough
mode also executes statements at the local database. To send statements to a
remote database without executing them locally you must supply the ONLY
keyword. The following set of statements drops a table not only at a remote
database, but also at the consolidated database.
-- Drop a table at the remote database
-- and at the local database
PASSTHROUGH TO Joe_Remote ;
DROP TABLE CrucialData ;
PASSTHROUGH STOP ;
The syntax to drop a table at the remote database only is as follows:
-- Drop a table at the remote database only
PASSTHROUGH ONLY TO Joe_Remote ;
DROP TABLE CrucialData ;
PASSTHROUGH STOP ;
The following are tasks that can be carried out on a running SQL Remote
setup:
♦ Add new users.
♦ Resynchronize users.

490
CHAPTER 19 Administering SQL Remote for Adaptive Server Anywhere

♦ Drop users from the setup.


♦ Change the address, message type, or frequency for a remote user.
♦ Add a column to a table.
Many other schema changes are likely to cause serious problems if executed
on a running SQL Remote setup.
Passthrough works In a multi-tier SQL Remote installation, it becomes important that
on only one level of passthrough statements work on the level of databases immediately beneath
a hierarchy the current level. In a multi-tier installation, passthrough statements must be
entered at each consolidated database, for the level beneath it.

Operations not replicated in passthrough mode


There are special considerations for some statements in passthrough mode.
Calling procedures When a stored procedure is called in passthrough mode using a CALL or
EXEC statement, the CALL statement itself is replicated and none of the
statements inside the procedure are replicated. It is assumed that the
procedure on the replicate side has the correct effect.
Control of flow Control-flow statements such as IF and LOOP, as well as any cursor
statements and operations, are not replicated in passthrough mode. Any statements within
cursor operations the loop or control structure are replicated.
Operations on cursors are not replicated. Inserting rows through a cursor,
updating rows in a cursor, or deleting rows through a cursor are not
replicated in passthrough mode.
Static embedded SQL SET OPTION statements are not replicated. The
following statement is not replicated in passthrough mode:
EXEC SQL SET OPTION . . .

However, the following dynamic SQL statement is replicated:


EXEC SQL EXECUTE IMMEDIATE "SET OPTION . . . "

Batches Batch statements ( a group of statements surrounded with a BEGIN and


END) are not replicated in passthrough mode. You receive an error message
if you try to use batch statements in passthrough mode.

491
Using passthrough mode

492
C H A P T E R 2 0

Administering SQL Remote for Adaptive


Server Enterprise

About this chapter This chapter details setup and management issues for SQL Remote
administrators using Adaptive Server Enterprise as the server for the
consolidated database.
Contents
Topic Page
How the Message Agent for Adaptive Server Enterprise works 494
Running the Message Agent 499
Error reporting and handling 501
Adaptive Server Enterprise transaction log and backup management 503
Making schema changes 506
Using passthrough mode 507

493
How the Message Agent for Adaptive Server Enterprise works

How the Message Agent for Adaptive Server


Enterprise works
This section describes how the Message Agent for Adaptive Server
Enterprise works. There are some significant differences between how the
Message Agent for Adaptive Server Enterprise and the Message Agent for
Adaptive Server Anywhere operate, which accommodate the different roles
of the two servers.
$ For information on features of the Message Agent that are common to
Adaptive Server Anywhere and Adaptive Server Enterprise, see "Running
the Message Agent" on page 454.
Message Agent is The Message Agent for Adaptive Server Enterprise is the following
ssremote executable:
♦ On Windows operating systems, the Message Agent is ssremote.exe
♦ On UNIX operating systems, the Message Agent is ssremote.

Scanning the transaction log


The Message Agent scans the Adaptive Server Enterprise transaction log in
order to collect transactions to be sent to remote databases. It stores these
transactions in a stable queue.
$ For more information about the stable queue, see "The stable queue" on
page 495. For more information about how the Message Agent uses the
stable queue, see "Message Agent operation phases" on page 496.
The SQL Remote Message Agent uses the same transaction log scanning
interface as the Adaptive Server Enterprise Log Transfer manager (LTM).
Adaptive Server Enterprise maintains a truncation point, which is an
identifier for the oldest page in the transaction log needed by the replication
system.
The SQL Remote Message Agent sets the truncation point as soon as
transactions are scanned from the transaction log and committed in the stable
queue. This allows the dump transaction command to reclaim space in the
transaction log as soon as possible. The Message Agent does not wait until
confirmation is received from remote databases before setting the truncation
point.

494
Chapter 20 Administering SQL Remote for Adaptive Server Enterprise

Message Agent must be run to reclaim log space


The Message Agent must be run frequently enough to prevent the
transaction log from running out of space. The dump transaction
command does not reclaim space from pages after the truncation point.

Replication Server Using SQL Remote on an Adaptive Server Enterprise database participating
and SQL Remote in a Replication Server setup may involve other considerations. If your
database has a replication agent (LTM) running against it, then you need to
use the SQL Remote Open Server as an additional component. Adaptive
Server Enterprise databases have replication agents running against them in
the following circumstances:
♦ The database is participating in a Replication Server setup as a primary
database, or
♦ The database is participating in a Replication Server setup and is using
asynchronous procedure calls.
If the database is participating in a Replication Server setup as a replicate
site, and no asynchronous procedure calls are being used, there is no need for
the SQL Remote Open Server.
$ For more information about the SQL Remote Open Server, see "Using
SQL Remote with Replication Server" on page 509.

The stable queue


The Message Agent for Adaptive Server Enterprise uses a stable queue to
hold transactions until they can be deleted. A stable queue is a pair of
database tables that hold messages that may still be needed by the replication
system.
SQL Remote for Adaptive Server Anywhere does not use a stable queue.

Stable queue not identical to Replication Server stable queue


Sybase Replication Server also uses stable queues as storage areas for
replication messages. The Replication Server and SQL Remote stable
queues perform similar functions, but are not the same thing.

Stable queue The stable queue may be kept in the same database as the tables being
location replicated, or in a different database. Keeping the stable queue in a separate
database complicates the backup and recovery plan, but can improve
performance by putting the stable queue workload on separate devices and/or
a separate Adaptive Server Enterprise server.

495
How the Message Agent for Adaptive Server Enterprise works

Do not modify the stable queue directly


The stable queue is maintained by and for the Message Agent. You should
not modify the stable queue directly.

The stable queue consists of a set of tables that contain information on all
transactions scanned from the transaction log,
$ For a description of each of the columns of these tables, see "Stable
Queue tables" on page 570.

Message Agent operation phases


The Message Agent has the following phases of execution:
♦ Receiving messages During this phase, the Message Agent receives
incoming messages and applies them to the Adaptive Server Enterprise
server.

Message system

Message
Agent

♦ Populating the stable queue During this phase the Message Agent
scans the Adaptive Server Enterprise transaction log into the stable
queue.

496
Chapter 20 Administering SQL Remote for Adaptive Server Enterprise

Transaction Stable
log queue

Message
Agent

♦ Sending messages During this phase, the Message Agent builds


outgoing messages from the stable queue.

Message system

Stable
queue

Message
Agent

497
How the Message Agent for Adaptive Server Enterprise works

The transactions remain in the stable queue until confirmation has been
received from all remote databases. When confirmation is received, the
transactions are automatically removed from the stable queue by the
Message Agent.
The Message Agent does not scan the transaction log of the database in
which the stable queue resides if it is different from the database with
SQL Remote system tables.
$ For information on running multiple copies of the Message Agent to
carry out these tasks, see "Running multiple Message Agents" on page 499.

498
Chapter 20 Administering SQL Remote for Adaptive Server Enterprise

Running the Message Agent


$ This section describes how to run the Message Agent for Adaptive
Server Enterprise. For information on features of the Message Agent that are
common to Adaptive Server Anywhere and Adaptive Server Enterprise, see
"Running the Message Agent" on page 454.

The Message Agent and replication security


In the tutorials earlier in this book, the Message Agent was run using a user
ID with system administrator permissions. The operations in the messages
are carried out from the user ID specified in the Message Agent connection
string; by using a system administrator user ID, you can be sure that the user
has permissions to make all the changes.
In practice, you will not use such a user ID, but the Message Agent needs to
run using a user ID with replication role. You can grant replication role with
the following statement:
sp_role ’grant’, replication_role, user_name

The user for the Message Agent must have insert, update and delete
permissions on all replicated tables, in order to apply the changes. Also, the
replication error procedure must be created under the Message Agent user
ID.
When you setup your Adaptive Server Enterprise database, the scripts
ssremote.sql and squeue.sql must be run under the same user name you use
for the Message Agent.
$ For setup instructions, see "Setting Up SQL Remote" on page 233.
To hide the user password for the Message Agent user ID, you can store the
ssremote command-line options in a file, and use ssremote with the
@filename parameter. You can use file system security to prevent
unauthorized access to the file.

Running multiple Message Agents


The three phases of Message Agent operation are described in the section
"Message Agent operation phases" on page 496. To summarize, these phases
are:
♦ Receiving messages.
♦ Scanning the transaction log.

499
Running the Message Agent

♦ Sending messages.
You may wish to run separate copies of the Message Agent to carry out these
different phases. You can specify which phases a given Message Agent is to
execute on the Message Agent command line.
Specifying which The command-line options are as follows:
phases to execute
♦ Receive The -r command-line switch instructs the Message Agent to
receive messages while it is running. To cause the Message Agent to
shut down after receiving available messages, use the -b switch in
addition to -r.
♦ Scan log The -i command-line switch instructs the Message Agent to
scan the transaction log into the stable queue while it is running.
♦ Send The -s command-line switch instructs the Message Agent to
send messages while it is running.
♦ Multiple phases If none of -r, -i, or -s is specified, the Message
Agent executes all three phases. Otherwise, only the indicated phases are
executed.
There are several circumstances where you may wish to run multiple
Message Agents.
♦ Ensuring the transaction log does not run out of space It is
important that the transaction log not be allowed to become full. For this
reason, you must scan the transaction log frequently enough to ensure
that all entries required by SQL Remote are placed in the stable queue.
Therefore, you may want to run a Message Agent that scans the
transaction log continuously, even if you are only receiving and sending
messages in batch mode.
♦ Mixing operating systems If you wish to use a message link
supported under Windows 95 or NT, you must use a Message Agent on
that platform to send and receive messages. You can do this, while
running the log scanning on a UNIX machine, by running two copies of
the Message Agent.

How Message The operations of two or more Message Agents are synchronized by a table
Agents are called sr_marker. This table has a single column called marker, of data
synchronized type datetime.
When the Message Agent wants to wait for transactions to be scanned into
the stable queue, it updates sr_marker and waits for it to work its way
through the system. The column in sr_queue_state is also called marker, and
contains the most recent marker to be scanned from the transaction log.

500
Chapter 20 Administering SQL Remote for Adaptive Server Enterprise

Error reporting and handling


This section describes how errors are reported and handled by the Message
Agent.

Default error handling


The default action taken by the Message Agent when an error occurs is to
record the fact in its log output. The Message Agent sends log output to a
window or a log file recording its operation. By default, log output is sent to
the window only; the -o command-line option sends output to a log file as
well.
The Message Agent may print more information in the output log than in the
window. The Message Agent log includes the following:
♦ Listing of messages applied.
♦ Listing of failed SQL statements.
♦ Listing of other errors.

UPDATE conflicts UPDATE conflicts are not errors, and so are not reported in the Message
are not errors Agent output.

Implementing error handling procedures


SQL Remote allows you to carry out some other process in addition to
logging a message if an error occurs. The REPLICATION_ERROR database
option allows you to specify a stored procedure to be executed by the
Message Agent when an error occurs. By default no procedure is executed .
The procedure must have a single argument of type CHAR or VARCHAR.
The procedure is called with any error messages and with the SQL statement
that causes the error.
While the option allows you to track and monitor errors in replication, you
must still design them out of your setup: this option is not intended to resolve
such errors.
For example, the procedure could insert the errors into a table with the
current time and remote user ID, and this information can then replicate back
to the consolidated database. An application at the consolidated database can
create a report or send e-mail to an administrator when errors show up.

501
Error reporting and handling

$ For information on setting the REPLICATION_ERROR option, see


"SQL Remote options" on page 542.

502
Chapter 20 Administering SQL Remote for Adaptive Server Enterprise

Adaptive Server Enterprise transaction log and


backup management
You must protect against losing transactions that have been replicated to
remote databases. If transactions are lost that have already been replicated to
remote databases, the remote databases will be inconsistent with the
consolidated database. In this situation, you may have to re-extract all remote
databases.

Protecting against media failure on the transaction log


Media failure on the transaction log can cause committed transactions to be
lost. If the transaction log has been scanned and these transactions have
already been sent to subscriber databases, then the subscribing databases
contain transactions that are lost from the publishing database, and the
databases are in an inconsistent state.
Why the The transaction log is needed, even after the entries have been scanned into
transaction log is the stable queue, to guard against media failure on the database file. If the
needed database is lost, it must be recovered to a point that includes every
transaction that may have been sent to remote databases.
This recovery is done by restoring a database dump and loading transaction
dumps to bring the database up to date. The last transaction dump restored is
the dump of the active transaction log at the time of the failure.
Protecting against There are two ways of protecting against inconsistency arising from media
transaction log loss failure on the transaction log:
♦ Mirror the transaction log When a device is mirrored, all writes to the
device are copied to a separate physical device.
♦ Only replicate backed-up transactions There is a command-line
switch for the Message Agent that prevents it from sending transactions
until they are backed up.

Mirroring the The only way to protect against media failure on the transaction log is by
transaction log mirroring the transaction log.
Disk mirroring can provide nonstop recovery in the event of media failure.
The disk mirror command causes an Adaptive Server Enterprise database
device to be duplicated—that is, all writes to the device are copied to a
separate physical device. If one of the devices fails, the other contains an up-
to-date copy of all transactions.

503
Adaptive Server Enterprise transaction log and backup management

$ For information on disk mirroring in Adaptive Server Enterprise, see


the chapter "Mirroring Database Devices", in the Adaptive Server Enterprise
System Administration Guide.
Replicating only The Message Agent also provides a command line switch (-u) that only
backed-up sends transactions that have been backup up. In Adaptive Server Enterprise,
transactions this means transactions complete before the latest dump database command
or dump transaction command.
Choosing an The goal of the strategy is to reduce the possibility of requiring re-extraction
approach of remote databases to an acceptable level. In large setups, the possibility
must be as close to zero as possible, as the cost of re-extraction (in terms of
down time) is very high.
♦ The Message Agent -u command-line switch can be used instead of
transaction log mirroring when recovery of all transactions in a
consolidated database is not needed and mirroring is considered too
expensive. This may be true in small setups or setups where there are no
local users on the consolidated database.
♦ The Message Agent -u command-line switch can also be used in
addition to mirroring to provide additional protection against total site
failure or double media failure.

Stable queue recovery issues


Keeping the stable queue in a separate database complicates backup and
recovery, as consistent versions of the two databases have to be recovered.
Normal recovery automatically restores the two databases to a consistent
state, but recovery from media failure takes some care. When restoring
database dumps and transaction dumps, it is important to recover the stable
queue to a consistent point.
Two procedures in the stable store database are provided to help with
recovery from media failure:
♦ sp_queue_dump_database This procedure is called whenever a
dump database is scanned from the transaction log.
♦ sp_queue_dump_transaction This procedure is called whenever a
dump transaction is scanned from the transaction log.
You can modify these stored procedures to issue dump database and dump
transaction commands in the stable store database.

504
Chapter 20 Administering SQL Remote for Adaptive Server Enterprise

Transaction log management


The Adaptive Server Enterprise log transfer interface allows the Message
Agent to scan the Adaptive Server Enterprise transaction log. When this
interface is being used, it sets a truncation point in the transaction log. The
truncation point prevents Adaptive Server Enterprise from re-using pages in
the transaction log before they have been scanned by SSREMOTE. For this
reason, DUMP TRANSACTION will not necessarily release transaction log
pages that are before the oldest open transaction. DUMP TRANSACTION
will not release transaction log pages beyond the "truncation point".
Initializing the The SQL Remote setup script (ssremote.sql) initializes the truncation point
truncation point with the following command
dbcc settrunc( ’ltm’, ’valid’ ).

The truncation point can be reset with the following command


dbcc settrunc( ’ltm’, ’ignore’ ).

This command tells Adaptive Server Enterprise to ignore the truncation


point, allowing transaction log pages beyond the truncation point to be
released for reuse. You should only use this command when you are no
longer interested in SQL Remote replication with the database and you want
to be able to reclaim space in the transaction device with DUMP
TRANSACTION commands. Continuing to run SQL Remote after ignoring
the truncation point will fail to replicate any transactions that were in
transaction log pages that were not scanned by the Message Agent and were
freed by DUMP TRANSACTION.

505
Making schema changes

Making schema changes


Schema changes to tables being replicated by SQL Remote must be made on
a quiet system. A quiet system means the following:
♦ No transactions being replicated There can be no transactions being
replicated that modify the tables that are to be altered. All transactions
that modify tables being altered must be scanned from the transaction
log into the stable queue before the schema is altered. This is performed
by running the Message Agent normally, or using the -i -b switches.
After the Message Agent completes, you can make the schema change..
♦ Message Agent The Message Agent must be shut down when the
schema change is being made.
♦ SQL Remote Open Server If you are using the SQL Remote Open
Server, it must be shut down when the schema change is being made.
Schema changes include changes to publications, such as adding articles or
modifying articles. However, creating or dropping subscriptions, and adding
or removing remote users do not need to be done on a quiet system.
In the Adaptive Server Enterprise transaction log, there is no information
recording table structure changes: the SQL Remote log scanning process gets
the table structure from the Adaptive Server Enterprise system tables.
Consequently, the Message Agent cannot scan an operation from the
transaction log that happened against the old table structure.
Information stored in the stable queue before the schema change uses the old
table definitions and information stored after the schema change uses the
new table definitions.
Passthrough mode can be used at the same time as the schema change to
make sure that schema changes at remote databases occur in the correct
sequence.

506
Chapter 20 Administering SQL Remote for Adaptive Server Enterprise

Using passthrough mode


The publisher of the consolidated database can directly intervene at remote
sites using a passthrough mode, which enables standard SQL statements to
be passed through to a remote site.
Determining Passthrough destinations are determined by sp_passthrough_user and
recipients of sp_passthrough_subscription. Executing either of these procedures
passthrough determines a set of recipients for any subsequent passthrough statements.
statements
Executing either sp_passthrough_user and sp_passthrough_subscription
adds to the current list of recipients. The sp_passthrough_stop procedure
resets passthrough (that is, resets the list of recipients to be empty).
In Adaptive Server Enterprise, sp_passthrough never executes statements in
the consolidated database. Passthrough SQL statements are applied only to
remote databases.
Passthrough To cause passthrough SQL statements to replicate, you call sp_passthrough.
statements
Due to the VARCHAR(255) limitation in Adaptive Server Enterprise, you
should build a long SQL statement up in pieces. Calls to
sp_passthrough_piece will build up a single SQL statement. Calling
sp_passthrough with the last piece will cause the built up statement to
replicate.
Notes on using ♦ You should always test your passthrough operations on a test database
passthrough mode with a remote database subscribed. You should never run untested
passthrough scripts against a production database.
♦ You should always qualify object names with the owner name.
PASSTHROUGH statements are not executed at remote databases from
the same user ID. Consequently, object names without the owner name
qualifier may not be resolved correctly.

Schema modifications
The Adaptive Server Enterprise log transfer interface does not contain
information about the number of columns and data types of the columns in a
table. SSREMOTE gets this information directly from the Adaptive Server
Enterprise system tables. For this reason, altering a table and then scanning
operations that happened before the ALTER TABLE will lead to errors.
SSREMOTE must set the "truncation point" beyond all operations on
replicated tables before schema changes can be made. Operations on
replicated tables need to be prevented between SSREMOTE running and the
schema changes being made.

507
Using passthrough mode

508
C H A P T E R 2 1

Using SQL Remote with Replication Server

About this chapter This chapter describes the additional components needed to use SQL Remote
on an Adaptive Server Enterprise database that also participates in a
Replication Server installation.
Contents
Topic Page
When you need to use the SQL Remote Open Server 510
Architecture for Replication Server/SQL Remote installations 511
Setting up SQL Remote Open Server 514
Configuring Replication Server 517
Other issues 519

509
When you need to use the SQL Remote Open Server

When you need to use the SQL Remote Open


Server
The Message Agent for Adaptive Server Enterprise scans the Adaptive
Server Enterprise transaction log to populate the stable queue, as described in
the section "The stable queue" on page 495). SQL Remote messages are built
from the transactions in the stable queue.
The Message Agent uses the same interface to scan the transaction log as the
Replication Agent for Adaptive Server Enterprise. This means the Message
Agent cannot scan the transaction log of an Enterprise database that is a
primary site in a Replication Server setup (or a replicate site that allows
asynchronous updates to primary data).
If there is a Replication Agent running against your Adaptive Server
Enterprise database, you must use the SQL Remote Open Server as an
additional component. In this case, SQL Remote is set up so that Replication
Server populates the stable queue. The SQL Remote Message Agent does not
scan the transaction log. Instead, the SQL Remote Open Server receives
transactions from Replication Server. The transactions are parsed by the
SQL Remote Open Server and stored in the SQL Remote stable queue.
$ This chapter assumes knowledge of Replication Server. For
information, see your Replication Server documentation.

Open Server runtime components required


The Open Server runtime components are not included with SQL Remote.
You must obtain them separately from Sybase in order to use the
SQL Remote Open Server.

510
Chapter 21 Using SQL Remote with Replication Server

Architecture for Replication Server/SQL Remote


installations
The arrangement for using a database as a Replication Server primary site
and as a SQL Remote database is illustrated in the following diagram. The
diagram illustrates a case where the stable queue is held in a different
database from the data being replicated. The stable queue may alternatively
be held in the same database as the data being replicated. All connections are
client/server connections, and so the components may be running on the
same or different machines.

SQL
Replication Remote
SQL Remote
Server Open
Open Server
Server

Replication Stable
Agent Queue

SQL Remote
Adaptive
Message
Server
Agent
Enterprise

To remote
databases

How the pieces fit together


The SQL Remote Open Server acts as a replicate database in the Replication
Server setup, and so replication definitions and subscriptions are required in
the Adaptive Server Enterprise database on all tables participating in
SQL Remote replication and on several of the SQL Remote system tables.

511
Architecture for Replication Server/SQL Remote installations

Contents of the All operations are replicated to the SQL Remote Open Server, which stores
stable queue them in the stable queue. The stable queue does not have copies of the tables
being replicated. It parses the inserts, updates, and deletes to build
transactions. All transactions are stored in an image column of a single table.
These transactions are used by the Message Agent to build SQL Remote
messages.

Message system

Stable
queue

Message
Agent

Incoming The Message Agent always applies incoming SQL Remote messages directly
messages to Adaptive Server Enterprise. It does not send operations to Replication
Server. Incoming messages are applied directly to the consolidated database
regardless of how the stable queue is populated. Conflict resolution is also
performed in the same way.

512
Chapter 21 Using SQL Remote with Replication Server

Message system

Message
Agent

Replication Server SQL Remote allows two-way replication between the consolidated database
and SQL Remote and remote databases. Replication Server is performing one-way replication
from the consolidated database to the SQL Remote Open Server. From
Replication Server’s perspective, transactions that originate in remote
SQL Remote databases appear as transactions originating in the consolidated
SQL Remote database.
SQL Remote The SQL Remote Open Server requires information from the SQL Remote
system tables system tables concerning publications and subscriptions. The Open Server
uses a connection to the Adaptive Server Enterprise database holding that
information to retrieve it when it starts.
If the SQL Remote system tables are updated while the Open Server is
running, the SQL Remote Open Server needs to receive this information at
the correct time. For this reason, some of the SQL Remote system tables
need to be marked for replication. This is described in "Setting up
SQL Remote Open Server" on page 514.
The SQL Remote The SQL Remote Open Server is the following executable:
Open Server
♦ On Windows operating systems, the SQL Remote Open Server is
executable
ssqueue.exe.
♦ On UNIX operating systems, the SQL Remote Open Server is ssqueue.

513
Setting up SQL Remote Open Server

Setting up SQL Remote Open Server


This section describes how to set up a SQL Remote installation using the
SQL Remote Open Server. The procedure depends on whether the
SQL Remote stable queue is being kept in a separate Adaptive Server
Enterprise database from the tables being replicated or in the same Adaptive
Server Enterprise database.
$ For more information about stable queue location, see "The stable
queue" on page 495.
Initial copies of the The setup procedure assumes you are using the extraction utility to produce
data an initial copy of the data in each remote database. You must be sure not to
use the Replication Server materialization feature for this purpose.
The procedure for setting up SQL Remote Open Server has two stages:
♦ Prepare a SQL Remote setup This stage depends on whether you
have an existing SQL Remote installation or not.
♦ Add the SQL Remote Open Server to the setup This stage is the
same regardless of previous installations.

v To prepare your SQL Remote setup, if you have an existing


SQL Remote installation:
1 On a quiet primary database, use the Message Agent to scan any
remaining transactions into the stable queue.
A quiet database is one where neither the Message Agent not the
SQL Remote Open Server is running, and where no transactions are
being replicated.
2 Follow the steps in the section "Upgrading SQL Remote for Adaptive
Server Enterprise" on page 239 to upgrade your SQL Remote software
at the consolidated site.
3 Invalidate the Message Agent truncation point at the consolidated
database using the following command:
dbcc settrunc(’ltm’, ’ignore’)
4 At the stable queue database, execute the stored procedure
sp_queue_log_transfer_reset.

v To prepare your SQL Remote setup, with no existing installation:


1 Set up SQL Remote as described in "Setting Up SQL Remote" on
page 233.

514
Chapter 21 Using SQL Remote with Replication Server

2 Set up your SQL Remote publications and subscriptions at this point.


For information on this procedure, see "SQL Remote Design for
Adaptive Server Enterprise" on page 369.
3 Extract the remote databases. For information on this procedure, see
"Using the extraction utility" on page 419.
You are now ready to set up the SQL Remote Open Server.

v To set up the SQL Remote Open Server:


1 If the SQL Remote stable queue is in a separate database:
♦ Set up the stable queue database as a replicate database in a
Replication Server setup. This will create the tables and procedures
needed by Replication Server, such as rs_lastcommit.
♦ Drop the Replication Server connection to the stable queue
database.
2 Add an entry to your interfaces file for the SQL Remote Open Server.
The default name used on the SQL Remote Open Server command line
is SSQueue.
3 Start the SQL Remote Open Server.
4 Create a Replication Server connection to the SQL Remote Open Server.
The user ID and password for this connection must match the user ID
and password specified on the SQL Remote Open Server command line
for the stable queue connection (that is, the -cq switch, or -c if -cq is
not specified).

Configure Replication Server now


You should configure Replication Server for this connection at this
point. For a description, see "Configuring Replication Server" on
page 517.

5 Define, activate, and validate Replication Server replication definitions


and subscriptions for the SQL Remote tables sr_marker,
sr_remoteuser, sr_subscription, and sr_passthrough. The script
ssremote.rs is a sample script to perform this task. You will need to edit
the server and database names in the script to match your names.
If the SQL Remote system tables have any data in them, create the
replication definitions so that no materialization happens.

515
Setting up SQL Remote Open Server

$ For information on creating replication definitions with no


materialization, see the Replication Server Administration Guide. The
section in Chapter 7, Managing Subscriptions entitled Bulk
Materialization describes how to set up Replication Server for the case
where data exists at a remote database.
6 Define, activate, and validate replication definitions and subscriptions
for the tables in your database that need to be replicated by
SQL Remote. These must be created without materialization.

516
Chapter 21 Using SQL Remote with Replication Server

Configuring Replication Server


This section describes how to configure Replication Server for use with the
SQL Remote Open Server
The Replication Server connection to the SQL Remote Open Server must
have several configuration parameters set.

Set the dsi_xact_group_size parameter


By default, Replication Server groups multiple transactions into larger
transactions. The dsi_xact_group_size parameter controls the maximum size
of a grouped transaction.
The dsi_xact_group_size parameter must be set to –1 to disable transaction
grouping. Transactions that originate from different remote databases in a
SQL Remote setup must not be grouped together.
How to set the You can set the parameter using the following statement:
parameter CONFIGURE CONNECTION TO "ssqueue_server"
SET dsi_xact_group_size TO ’-1’

Set the dsi_num_threads parameter


The SQL Remote Open Server does not support multiple DSI threads.
Replication Server should not be configured to use multiple DSI threads on
SQL Remote connections.

Create replication definitions for SQL Remote data


Replication definitions for tables being replicated by SQL Remote must have
certain characteristics. This section describes those characteristics.
In some circumstances SQL Remote replicates an UPDATE operation as an
INSERT or a DELETE (see "Replication of updates" on page 303). This is
referred to as subscription migration in the Replication Server
documentation. In order to replicate an UPDATE as an INSERT,
SQL Remote requires the full pre-image of the row. This means that
Replication Server must specify the values of every column in the WHERE
clause of any UPDATE to a table that might need to be replicated as an
INSERT.

517
Configuring Replication Server

The simplest way to achieve this is to list all columns in the PRIMARY KEY
of the replication definition. This forces Replication Server to include every
column in the WHERE clause of every update. REPLICATE MINIMAL
COLUMNS can be used on these replication definitions to prevent every
column from being listed in the SET clause of the update.
Text and image Replication Server does not accept TEXT or IMAGE columns in the primary
columns key of a replication definition. You should include all the columns except for
the TEXT and IMAGE columns in the PRIMARY KEY list of your
replication definition, and specify all the TEXT and IMAGE columns in the
ALWAYS_REPLICATE clause. You should use REPLICATE ALL
COLUMNS, instead of REPLICATE MINIMAL COLUMNS in your
replication definition. This forces Replication Server to send the pre-image
of the TEXT and IMAGE columns to the SQL Remote Open Server
whenever an update occurs.
Using the Replication Server 11.5 has a new dsi_sql_data_style for SQL Remote. This
dsi_sql_data_style data style automatically includes all columns in the WHERE clause of every
data style UPDATE. It is not necessary to list all columns in the PRIMARY KEY of
the replication definition. A replication definition using REPLICATE
MINIMAL COLUMNS prevents Replication Server from keeping the full
pre-image of rows being updated, so the SQL Remote dsi_sql_data_style
will not work with REPLICATE MINIMAL COLUMNS.

Suspend and restart the connection


After configuring the Replication Server connection to the SQL Remote
Open Server, you should suspend and resume the connection so that the
parameter settings can take effect. The following commands accomplish this
task:
suspend connection to ssqueue_server
go
resume connection to ssqueue_server
go

518
Chapter 21 Using SQL Remote with Replication Server

Other issues
This section lists other issues regarding using SQL Remote with Replication
Server.

Running the Message Agent The Message Agent should be run with
command line switches to receive and send (-r and -s). This will prevent the
Message Agent from attempting to scan the transaction log. If the Message
Agent attempts to scan the transaction log while the Replication Agent is
running, it will get an error attempting to reserve the "log transfer context".

Procedure calls in SQL Remote Open Server The SQL Remote Open
Server passes all procedure calls it receives from Replication Server through
to the stable queue database. For example, rs_get_lastcommit and
rs_update_lastcommit are executed in the stable queue database.

Coordinated dumps Replication Server provides a mechanism to


coordinate database dumps and transaction log dumps between the main
database and the stable queue database. The rs_dumpdb and rs_dumptran
function strings can be used to perform coordinated dumps of the stable
queue database. Please see the Replication Server documentation for more
information.

Schema changes If you make any schema changes to a SQL Remote


installation, you must do so on a quiet system. This includes shutting down
the SQL Remote Open Server.

519
Other issues

520
C H A P T E R 2 2

Utilities and Options Reference

About this chapter This chapter provides reference material for the SQL Remote command line
utilities and SQL Remote database options.
Contents
Topic Page
The Message Agent 522
The Database Extraction utility 531
The SQL Remote Open Server 539
SQL Remote options 542

521
The Message Agent

The Message Agent


Purpose To send and apply SQL Remote messages, and to maintain the message
tracking system to ensure message delivery.
Syntax { dbremote | ssremote } [ switches ] [ directory ]
Command-line Switch Description
switches
@filename Read in switches from configuration file
@envvar Read in switches from environment variable
–a Do not apply received transactions
–b Run in batch mode
–c "keyword=value; ..." Supply database connection parameters
–cq "keyword=value; ..." Supply database connection parameters for the stable
queue (Adaptive Server Enterprise only)
–dl Display log messages on screen
–e locale-string Locale setting (Adaptive Server Enterprise only)
–fq Full scan of the stable queue when sending messages
(Adaptive Server Enterprise only)
–g n Group transactions consisting of less than n
operations.
–i Scan transactions from the transaction log into the
stable queue (Adaptive Server Enterprise only).
–k Close window on completion
–l length Maximum message length
–m size Maximum amount of memory used for building
messages.
–o file Output messages to file
–os file Maximum file size for logging output messages
–ot file Truncate file and log output messages
–p Do not purge messages
–q Run with minimized window
–r Receive messages
–rd minutes Polling frequency for incoming messages
–rp number Number of receive polls before message is assumed
lost
–ru time Waiting period to re-scan log on receipt of a resend.

522
Chapter 22 Utilities and Options Reference

Switch Description
–s Send messages
–sd time Send polling period
–t Replicate all triggers (Adaptive Server Anywhere
only)
–u Process only backed up transactions
–ud On UNIX platforms, run as a daemon.
–v Verbose operation
–w n Number of worker threads to apply incoming
messages (Windows NT and Solaris only)
–x Rename and restart the transaction log (Adaptive
Server Anywhere only).
directory The directory in which old transaction logs are held
(Adaptive Server Anywhere only)

Description The Message Agent sends and applies messages for SQL Remote replication,
and maintains the message tracking system to ensure message delivery.
The name of the Message Agent executable is as follows:
♦ dbremote The Message Agent for Adaptive Server Anywhere.
♦ ssremote The Message Agent for Adaptive Server Enterprise.
You can also run the Message Agent from your own application by calling
into the DBTools library. For more information, see the file dbrmt.h in the h
subdirectory of your SQL Remote installation directory.
For Adaptive Server Anywhere, the user ID in the Message Agent command
line must have either REMOTE DBA or DBA authority. For Adaptive
Server Enterprise, the user ID must have replication role.
The optional directory parameter specifies a directory in which old
transaction logs are held, so that the Message Agent has access to events
from before the current log was started.
The Message Agent uses a number of connections to the database. For a
listing, see "Connections used by the Message Agent" on page 455.
$ For information on REMOTE DBA authority, see "The Message Agent
and replication security" on page 473.
Command-line @filename Read in command-line switches from the supplied file.
switch details

523
The Message Agent

The file may contain line breaks, and may contain any set of command line
switches. For example, the following command file holds a set of command
line switches for a Message Agent that starts with a cache size of 4 Mb,
sends messages only, and connects to a database named field on a server
named myserver:
-m 4096
-s
-c "eng=myserver;dbn=field;uid=sa;pwd=sysadmin"

If this configuration file is saved as c:\config.txt, it can be used in an


command line as follows:
ssremote @c:\config.txt
or
dbremote @c:\config.txt

@environment-variable Read in command-line switches from the


supplied environment variable.

The environment variable may contain any set of command line switches.
For example, the first of the following pair of statements sets an environment
variable holding a set of command line switches for a database server that
starts with a cache size of 4 Mb, receives messages only, and connects to a
database named field on a server named myserver. The set statement should
be entered all on one line:
set envvar=-m 4096 -r
-c "eng=myserver;dbn=field;uid=sa;pwd=sysadmin"
ssremote @envvar

–a Process the received messages (those in the inbox) without applying


them to the database. Used together with -v (for verbose output) and -p (so
the messages are not purged), this flag can help detect problems with
incoming messages. Used without -p, this flag purges the inbox without
applying the messages, which may be useful if a subscription is being
restarted.

–b Run in batch mode. In this mode, the Message Agent processes


incoming messages, scans the transaction log once and processes outgoing
messages, and then stops.
–c "parameter=value; ..." Specify connection parameters. For Adaptive
Server Anywhere, if this option is not specified, the environment variable
SQLCONNECT is used.
For example, the following statement runs dbremote on a database file
named c:\asa6\asademo.db, connecting with user ID DBA and password
SQL:

524
Chapter 22 Utilities and Options Reference

dbremote -c "uid=DBA;pwd=SQL;dbf=c:\asa6\asademo.db"
The Message Agent must be run by a user with REMOTE DBA authority or
DBA authority.
$ For information on REMOTE DBA authority, see "The Message Agent
and replication security" on page 473.
The Message Agent for Adaptive Server Anywhere supports the full range of
Adaptive Server Anywhere connection parameters. The Message Agent for
Adaptive Server Enterprise supports the following connection parameters:

Parameter Description
UID Login ID
PWD Password
DBN (optional) Database name. If this parameter is not supplied, the
connection defaults to the default database for the login ID.
ENG Adaptive Server Enterprise name.

–cq "parameter=value; ..." Specify connection parameters for the stable


queue. This option applies to Adaptive Server Enterprise only. If not
supplied, the values default to the -c values.

–dl Display messages in the Message Agent window or on the command


line and also in the log file if specified.
–e locale-string This option applies to Adaptive Server Enterprise only.
Specify Adaptive Server Enterprise locale information. The locale string has
the following format:
"language_name,charset_name[,sort_order]"
By default, the Message Agent uses the default locale, which is defined in
the file sybase\locales\locales.dat.
If language_name and charset_name are not supplied, the Message Agent
obtains them from Adaptive Server Enterprise. If sort_order is not supplied,
the Message Agent uses a binary sort order (sort by byte value).

–fq This option is for use only with Adaptive Server Enterprise. It permits
a a full scan of the stable queue when sending messages, starting from the
oldest confirm_sent value in the sr_remoteuser table.

525
The Message Agent

This feature is intended for occasional use to clean out a large stable queue.
If, for example, a single user has not confirmed receipt of a message from a
long time ago, the stable queue may be very large. However, by running -fq
you can delete entries from more up-to-date users that have been confirmed,
even though they are more recent than the cutoff value at which entries are
deleted by default.
–g n Instructs the Message Agent to group transactions containing less
than n operations together with transactions that follow. The default is
twenty operations. Increasing the value of n can speed up processing of
incoming messages, by doing less commits. However, it can also cause
deadlock and blocking by increasing the size of transactions.

–i Scan transactions from the transaction log into the stable queue. This
option is available for Adaptive Server Enterprise only. It is used when you
wish to run a separate copy of the Message Agent for scanning the
transaction log and for sending and receiving messages.
If none of -r, -i, or -s is specified, the Message Agent executes all three
phases. Otherwise, only the indicated phases are executed.
$ For more information, see "Running multiple Message Agents" on
page 499.

–k Close window on completion.

–l length Specifies the maximum length of each message to be sent, in


bytes. Longer transactions are split into more than one message. The default
is 50000 bytes and the minim length is 10000.

Caution
The maximum message length must be the same at all sites in an
installation.

For platforms with restricted memory allocation, the value must be less than
the maximum memory allocation of the operating system. For example,
Windows 3.x allows a maximum memory allocation of 64K, and the
maximum message length must be less than this.

–m size Specifies a maximum amount of memory to be used by the


Message Agent for building messages and caching incoming messages. The
allowed size can be specified as n (in bytes), nK, or nM. The default is
2048K (2M).

526
Chapter 22 Utilities and Options Reference

When all remote databases are receiving unique subsets of the operations
being replicated, a separate message for each remote database is built up
concurrently. Only one message is built for a group of remote users that are
receiving the same operations. When the memory being used exceeds the -m
value, messages are sent before reaching their maximum size (as specified by
the -l switch).
When messages arrive, they are stored in memory by the Message Agent
until they are applied. This caching of messages prevents rereading of that
are out of order messages from the message system , which may lower
performance on large installations. When the memory usage specified using
the -m switch is exceeded, messages are flushed in a least-recently used
fashion.

–o Append output to a log file. Default is to send output to the screen.

–os Specifies the maximum file size for logging output messages. The
allowed size can be specified as n (bytes), nK (Kb), or nM (Mb). By default
there is no limit, and the minimum limit is 10000 bytes.
Before SQL Remote logs output messages to a file, it checks the current file
size. If the log message will make the filesize exceed the specified size,
SQL Remote renames the output file to yymmddnn.dbr (for dbremote) and
yymmddnn.ssr (for ssremote) where nn is an integer from 00 to 99 and
yymmdd represents the current year, month, and date.
If the Message Agent us running in continuous mode for a long time, this
option allows you to manually delete old log files and free up disk space.

–ot Truncate the log file and then append output messages to it. Default is
to send output to the screen.

–p Process the messages without purging them.

–q For Windowing operating systems only, starts the Message Agent with
a minimized window.
–r Receive messages. If none of -r, -i, or -s is specified, the Message
Agent executes all three phases. Otherwise, only the indicated phases are
executed.
The Message Agent runs in continuous mode if called with -r. To have the
Message Agent shut down after receiving messages, use the -b switch in
addition to -r.

527
The Message Agent

–rd time By default, the Message Agent polls for incoming messages
every minute. This option (rd stands for receive delay) allows the polling
frequency to be configured, which is useful when polling is expensive. The
Message Agent checks for incoming messages once after each send cycle,
regardless of the polling frequency, so if a value greater then the SEND
EVERY frequency is supplied, the Message Agent checks for incoming
messages once after each send cycle.
You can use a suffix of s after the number to indicate seconds, which may be
useful if you want frequent polling. For example:
dbremote -rd 30s
polls every thirty seconds.
$ For more information on polling, see "Tuning incoming message
polling" on page 460.

–rp When running in continuous mode, the Message Agent polls at certain
intervals for messages. After polling a set number of times (by default, one),
if a message is missing, the Message Agent assumes it has got lost and
requests that it be resent. On slow message systems, this can result in many
unnecessary resend requests. You can set the number of polls before a resend
request is issued using this option, to cut down on the number of resend
requests.
$ For more information on configuring this option, see "Tuning incoming
message polling" on page 460.
–ru Control the resend urgency. This is the time between detection of a
resend request and when the Message Agent starts fulfilling the request. Use
this switch to help the Message Agent collect resend requests from multiple
users before rescanning the log. The time unit can be any of {s = seconds; m
= minutes; h = hours; d = days}
–s Send messages. If none of -r, -i, or -s is specified, the Message Agent
executes all three phases. Otherwise, only the indicated phases are executed.

–sd time Control the send delay which is the time to wait between polls
for more transaction log data to send.

–t All trigger actions are replicated. If you do use this switch, you must
ensure that the trigger actions are not carried out twice at remote databases,
once by the trigger being fired at the remote site, and once by the explicit
application of the replicated actions from the consolidated database.

To ensure that trigger actions are not carried out twice, you can wrap an IF
CURRENT REMOTE USER IS NULL ... END IF statement around the
body of the triggers. This option is available for Adaptive Server Anywhere
only.

528
Chapter 22 Utilities and Options Reference

–u Process only transactions that have been backed up. This switch
prevents the Message Agent from processing transactions since the latest
backup. Using this switch, outgoing transactions and confirmation of
incoming transactions are not sent until they have been backed up.
In Adaptive Server Anywhere, this means only transactions from renamed
logs are processed. In Adaptive Server Enterprise, this means that only
transactions committed before the latest dump database or dump
transaction statement are processed.

–ud On UNIX platforms, you can run the Message Agent as a daemon by
supplying the -ud command-line option.
If you run the Message Agent as a daemon, you must also supply the -o or
-ot command-line option, to log output information.
If you run the Message Agent as a daemon and are using FTP or SMTP
message links, you must store the message link parameters in the database,
because the Message Agent does not prompt the user for these options when
running as a daemon.
$ For information on message link parameters, see "Setting message type
control parameters" on page 445.

–v Verbose output. This switch displays the SQL statements contained in


the messages to the screen and, if the -o or -ot switch is used, to a log file.

–w n The number of worker threads used to apply incoming messages. The


default is zero, which means all messages are applied by the main (and only)
thread. A value of 1 (one) would have one thread receiving messages from
the message system and one thread applying messages to the database.
The -w switch makes it possible to increase the throughput of incoming
messages with hardware upgrades. Putting the consolidated database on a
device that can perform many concurrent operations (a RAID array with a
striped logical drive) will improve throughput of incoming messages.
Multiple processors in the computer running the Message Agent could also
improve throughput of incoming messages.
The -w switch will not improve performance significantly on hardware that
cannot perform many concurrent operations.
Incoming messages from a single remote database will never be applied on
multiple threads. Messages from a single remote database are always applied
serially in the correct order.
This option is not available on Windows 3.x.

529
The Message Agent

–x Rename and restart the transaction log after it has been scanned for
outgoing messages. In some circumstances, replicating data to a consolidated
database can take the place of backing up remote databases, or renaming the
transaction log when the database server is shut down. This option is
available for Adaptive Server Anywhere only.
Message system SQL Remote uses several registry settings (in Windows 95 and NT) or
control parameters initialization file settings (Windows 3.x and OS/2) to control aspects of
message link behavior.
The message link control parameters are stored in the following places:
♦ Windows 95 and Windows NT In the registry, at the following
location:
\\HKEY_CURRENT_USER
\Software
\Sybase
\SQL Remote
♦ Windows 3.x and OS/2 In the file SQLANY.INI, in your
SQL Remote installation directory.
♦ NetWare You should create a file named dbremote.ini in the
sys:\system directory to hold the FILE system directory setting.

$ For a listing of registry settings, see the section for each message
system under "Using message types" on page 441.

530
Chapter 22 Utilities and Options Reference

The Database Extraction utility


You can access the remote database extraction utility in the following ways:
♦ From Sybase Central, for interactive use under Windows 95 or NT.
♦ From the system command line, using the ssxtract or dbxtract command-
line utilities. This is useful for incorporating into batch or command
files.
ssxtract is the extraction utility for Adaptive Server Enterprise, dbxtract
is the extraction utility for Adaptive Server Anywhere.
By default, the extraction utility runs at isolation level zero. If you are
extracting a database from an active server, you should run it at isolation
level 3 (see "Extraction utility options" on page 534) to ensure that data in
the extracted database is consistent with data on the server. Running at
isolation level 3 may hamper others’ turnaround time on the server because
of the large number of locks required. It is recommended that you run the
extraction utility when the server is not busy, or run it against a copy of the
database (see "Designing an efficient extraction procedure" on page 422).
Objects owned by The dbo user ID owns a set of Adaptive Server Enterprise-compatible
dbo system objects in an Adaptive Server Anywhere database.
For Adaptive Server Anywhere, the extraction utility does not unload the
objects created for the dbo user ID during database creation. Changes made
to these objects, such as redefining a system procedure, are lost when the
data is unloaded. Any objects created by the dbo user ID since the
initialization of the database are unloaded by the Extraction utility, and so
these objects are preserved.

Extracting a remote database in Sybase Central


Running the extraction utility from Sybase Central carries out the following
tasks related to creating and synchronizing SQL Remote subscriptions:
♦ Creates a command file to build a remote database containing a copy of
the data in a specified publication.
♦ Creates the necessary SQL Remote objects, such as message types,
publisher and remote user IDs, publication and subscription, for the
remote database to receive messages from and send messages to the
consolidated database.
♦ Starts the subscription at both the consolidated and remote databases.

531
The Database Extraction utility

v To extract a remote database from a running database


1 Connect to the database.
2 Right-click the database and choose Extract Database from the popup
menu.
3 Follow the instructions in the wizard.

v To extract a remote database from a database file or a running


database
1 Open the Utilities folder.
2 In the right pane, double-click Extract Database.
3 Follow the instructions in the wizard.

The extraction command-line utility


Purpose To extract a remote Adaptive Server Anywhere database from a consolidated
Adaptive Server Enterprise or Adaptive Server Anywhere database.
Syntax { ssxtract | dbxtract } [ switches ] [ directory ] subscriber

Switch Description
–an database Creates a database file with the same settings as the
database being unloaded and automatically reloads it.
–ac "keyword=value; ..." Connect to the database specified in the connect string to do
the reload.
–b Do not start subscriptions
–c "keyword=value; ..." Supply database connection parameters
–d Unload data only
–e language,charset Specify the locale to be used
–f Extract fully qualified publications
–ii Internal unload, internal reload
–ix Internal unload, external reload
–j count Iteration count for view creation statements
–l level Perform all extraction operations at specified isolation level
–k Close window on completion
–n Extract schema definition only
–o file Output messages to file

532
Chapter 22 Utilities and Options Reference

Switch Description
–p character Escape character
–q Operate quietly: do not print messages or show windows
–r file Specify name of generated reload Interactive SQL command
file (default "reload.sql")
–u Unordered data
–v Verbose messages
–x Use external table loads
–xf Exclude foreign keys
–xi External unload, internal reload
–xp Exclude stored procedures
–xt Exclude triggers
–xv Exclude views
–xx External unload, external load
–y Overwrite command file without confirmation
directory The directory to which the files are written. This is not
needed if you use -an or -ac
subscriber The subscriber for whom the database is to be extracted.

Description ssxtract is the extraction utility for Adaptive Server Enterprise. It is run
against a Adaptive Server Enterprise and creates a command file for a remote
Adaptive Server Anywhere database.
dbxtract is the extraction utility for Adaptive Server Anywhere. It is run
against an Adaptive Server Anywhere database and creates a command file
for a remote Adaptive Server Anywhere database.
There is no extraction utility to create remote Adaptive Server Enterprise
databases.
The command line extraction utility creates a command file and a set of
associated data files. The command file can be run against a newly-
initialized Adaptive Server Anywhere database to create the database objects
and load the data for the remote database.
By default, the command file is named reload.sql.
If the remote user is a group, then all the user IDs that are members of that
group are extracted. This allows multiple users on a remote database with
different user IDs, without requiring a custom extraction process.

533
The Database Extraction utility

SSXtract notes Not all Adaptive Server Enterprise objects have corresponding objects in
Adaptive Server Anywhere. The ssxtract utility has the following limitations:
♦ Single database All extracted objects must be in a single Adaptive
Server Enterprise database.
♦ Passwords The password for the extracted user IDs are the same as
the user ID itself.
♦ Permissions The extracted user ID is granted REMOTE DBA
authority.
♦ Named constraints These are extracted as Adaptive Server Anywhere
CHECK constraints.
♦ System tables The sp_populate_sql_anywhere SQL Remote
procedure builds a set of Adaptive Server Anywhere system tables in
TEMPDB from the Adaptive Server Enterprise system tables. The
extracted schema comes from these temporary system tables.
$ For more information about the command-line switches, see
"Extraction utility options" on page 534.

Extraction utility options


Create a database for reloading (–an) You can combine the operations
of unloading a database, creating a new database, and loading the data using
this option.
For example, the following command (which should be entered all on one
line) creates a new database file named asacopy.db and copies the schema
and data for the field_user subscriber of asademo.db into it:
dbxtract -c "uid=dba;pwd=sql;dbf=asademo.db" -an
asacopy.db field_user
If you use this option, no copy of the data is created on disk, so you do not
specify an unload directory on the command line. This provides greater
security for your data, but at some cost for performance.

Reload the data to an existing database (–ac) You can combine the
operation of unloading a database and reloading the results into an existing
database using this option.
For example, the following command (which should be entered all on one
line) loads a copy of the data for the field_user subscriber into an existing
database file named newdemo.db:
dbxtract -c "uid=dba;pwd=sql;dbf=asademo.db" -ac
"uid=dba;pwd=sql;dbf=newdemo.db" field_user

534
Chapter 22 Utilities and Options Reference

If you use this option, no copy of the data is created on disk, so you do not
specify an unload directory on the command line. This provides greater
security for your data, but at some cost for performance.

Do not start subscriptions automatically (–b) If this option is selected,


subscriptions at the consolidated database (for the remote database) and at
the remote database (for the consolidated database) must be started explicitly
using the START SUBSCRIPTION statement for replication to begin.

Connection parameters (–c) A set of connection parameters, in a string.


♦ dbxtract connection parameters The user ID should have DBA
authority to ensure that the user has permissions on all the tables in the
database.
For example, the following statement (which should be typed on one
line) extracts a database for remote user ID joe_remote from the
asademo database running on the sample_server server, connecting as
user ID DBA with password SQL. The data is unloaded into the
c:\unload directory.
ssxtract -c "eng=sample_server;dbn=sademo;
uid=dba;pwd=sql" c:\extract joe_remote
If connection parameters are not specified, connection parameters from
the SQLCONNECT environment variable are used, if set.
♦ ssxtract connection parameters The following connection
parameters are supported:

Parameter Description
UID Login ID
PWD Password
DBN (optional) Database name. If this parameter is not supplied,
the connection defaults to the default database for the login
ID.
ENG Adaptive Server Enterprise name.

ssxtract cannot extract passwords. It sets passwords to be the same as


the user ID.

Unload the data only (–d) If this option is selected, the schema definition
is not unloaded, and publications and subscriptions are not created at the
remote database. This option is for use when a remote database already exists
with the proper schema, and needs only to be filled with data.

535
The Database Extraction utility

Use specified locale (–e) This option applies to Adaptive Server


Enterprise only.
Specify Adaptive Server Enterprise locale information. The locale string has
the following format:
"language_name,charset_name[,sort_order]"
By default, the Message Agent uses the default locale, which is defined in
the file sybase\locales\locales.dat.
If language_name and charset_name are not supplied, the Message Agent
obtains them from Adaptive Server Enterprise. If sort_order is not supplied,
the Message Agent uses a binary sort order (sort by byte value).

Extract fully qualified publications (–f) In most cases, you do not need
to extract fully qualified publication definitions for the remote database,
since it typically replicates all rows back to the consolidated database
anyway.

However, you may want fully qualified publications for multi-tier setups or
for setups where the remote database has rows that are not in the
consolidated database.

Internal unload, internal load (–ii) Using this option forces the reload
script to use the internal UNLOAD and LOAD TABLE statements rather
than the Interactive SQL OUTPUT and INPUT statements to unload and
load data, respectively.
This combination of operations is the default behavior.
External operations takes the path of the data files relative to the current
working directory of dbxtract, while internal statements take the path relative
to the server.

Internal unload, external load (–ix) Using this option forces the reload
script to use the internal UNLOAD statement to unload data, and the
Interactive SQL INPUT statement to load the data into the new database.
External operations takes the path of the data files relative to the current
working directory of dbxtract, while internal statements take the path relative
to the server.

Iteration count for views (–j) If there are nested views in the
consolidated database, this option specifies the maximum number of
iterations to use when extracting the views.

536
Chapter 22 Utilities and Options Reference

Perform extraction at a specified isolation level (–l) The default


setting is an isolation level of zero. If you are extracting a database from an
active server, you should run it at isolation level 3 (see "Extraction utility
options" on page 534) to ensure that data in the extracted database is
consistent with data on the server. Increasing the isolation level may result in
large numbers of locks being used by the extraction utility, and may restrict
database use by other users.

Unload the schema definition only (–n) With this definition, none of
the data is unloaded. The reload file contains SQL statements to build the
database structure only. You can use the SYNCHRONIZE SUBSCRIPTION
statement to load the data over the messaging system. Publications,
subscriptions, PUBLISH and SUBSCRIBE permissions are part of the
schema.

Output messages to file (–o) Outputs the messages from the extraction
process to a file for later review.

Escape character (–p) The default escape character (\) can be replaced
by another character using this option.

Operate quietly (–q) Display no messages except errors. This option is


not available from other environments. This is available only from the
command-line utility.

Reload filename (–r) The default name for the reload command file is
reload.sql in the current directory You can specify a different file name with
this option.

Output the data unordered (–u) By default the data in each table is
ordered by primary key. Unloads are quicker with the -u switch, but loading
the data into the remote database is slower.

Verbose mode (–v) The name of the table being unloaded and the
number of rows unloaded are displayed. The SELECT statement used is also
displayed.

Exclude foreign key definitions (–xf) You can use this if the remote
database contains a subset of the consolidated database schema, and some
foreign key references are not present in the remote database.

External unload, internal load (–xi) The default behavior for unloading
the database is to use the UNLOAD statement, which is executed by the
database server. If you choose an external unload, dbxtract uses the
OUTPUT statement instead. The OUTPUT statement is executed at the
client.

537
The Database Extraction utility

External operations takes the path of the data files relative to the current
working directory of dbxtract, while internal statements take the path relative
to the server.

Exclude stored procedure (–xp) Do not extract stored procedures from


the database.

Exclude triggers (–xt) Do not extract triggers from the database.

Exclude views (–xv) Do not extract views from the database.

External unload, external load (–xx) Use the OUTPUT statement to


unload the data, and the INPUT statement to load the data into the new
database.

The default unload behavior is to use the UNLOAD statement, and the
default loading behavior is to use the LOAD TABLE statement. The internal
UNLOAD and LOAD TABLE statements are faster than OUTPUT and
INPUT.
External operations takes the path of the data files relative to the current
working directory of dbxtract, while internal statements take the path relative
to the server.

Operate without confirming actions (–y) Without this option, you are
prompted to confirm the replacement of an existing command file.

538
Chapter 22 Utilities and Options Reference

The SQL Remote Open Server


Purpose To take replication data from Replication Server and apply it to the
SQL Remote stable queue. This utility is needed only for databases
participating in both Replication Server (and using a Replication Agent) and
SQL Remote replication.
Syntax ssqueue [ switches ] [ open-server-name ]
Command-line Switch Description
switches
open-server-name An open server name, which must be declared in the
interfaces file.
–c "keyword=value; ..." Supply database connection parameters
–cq "keyword=value; ..." Supply database connection parameters for the stable
queue
–dl Display messages in window
–k Close window on completion
–o file Output messages to file
–os file Maximum file size for logging output messages
–ot file Truncate file and log output messages
–q Run with minimized window
–ud Run as a daemon [UNIX]
–v Verbose operation

Description The SQL Remote Open Server is used to enable an Adaptive Server
Enterprise database to take part in both SQL Remote replication while acting
as a primary site in a Replication Server installation (or a replicate site using
asynchronous procedure calls).
The name of the executable is as follows:
♦ ssqueue.exe Windows NT platforms.
♦ ssqueue UNIX platforms.

Command-line open-server-name Replication Server must connect to the SQL Remote


switch details Open Server, which therefore must have an open server name. This open
server name is set on the command line, and must correspond to a master and
query entry in the interfaces file on the machine running the SQL Remote
Open Server, and to a query entry on the interfaces file of the machine
running Replication Server.

539
The SQL Remote Open Server

The interfaces file is named sql.ini on Windows operating systems, and


interfaces on UNIX.
The default value for the open server name is SSQueue.
–c Specify connection parameters to the database holding the data being
replicated. This connection is required for the SQL Remote Open Server to
gain access to the SQL Remote system tables.
The connection parameters must come from the following list:

Parameter Description
UID Login ID
PWD Password
DBN (optional) Database name. If this parameter is not supplied, the
connection defaults to the default database for the login ID.
ENG Server name.

–cq Specify connection parameters for the stable queue. If not supplied,
the values default to the -c values.

–dl Display messages in the window or on the command line and also in
the log file.

–k Close window on completion.

–o Append output to a log file. Default is to send output to the screen.

–os Specifies the maximum file size for logging output messages. The
allowed size can be specified as n (bytes), nK (kb), or nM (Mb). By default
there is no limit, and the minimum limit is 10000 bytes.
Before SQL Remote logs output messages to a file, it checks the current file
size. If the log message will make the filesize exceed the specified size,
SQL Remote renames the output file to yymmddnn.dbr (for dbremote) and
yymmddnn.ssr (for ssremote) where nn is an integer from 00 to 99 and
yymmdd represents the current year, month, and date.
If the Message Agent us running in continuous mode for a long time, this
option allows you to manually delete old log files and free up disk space.

–ot Truncate the log file and then append output messages to it. Default is
to send output to the screen.

–q For Windowing operating systems only, starts the Message Agent with
a minimized window.

540
Chapter 22 Utilities and Options Reference

–ud On UNIX platforms, you can run the SQL Remote Open Server as a
daemon by supplying the -ud command-line option.
If you run as a daemon, you must also supply the -o or -ot command-line
option, to log output information.

–v Verbose output. This switch displays the SQL statements contained in


the messages to the screen and, if the -o switch is used, to a log file.

541
SQL Remote options

SQL Remote options


Function Replication options are database options included to provide control over
replication behavior.
Anywhere Syntax SET [ TEMPORARY ] OPTION
... [ userid. | PUBLIC. ]option_name = [ option_value ]
Enterprise syntax: exec sp_remote_option option-name, option-value
Parameters Argument Description
option_name The name of the option being changed.
option-value A string containing the setting for the option.

Description The following options are available.

OPTION VALUES DEFAULT


Blob_threshold integer, in kb 256
Compression –1 to 9 6
Delete_old_logs ON, OFF OFF
External_remote_options ON, OFF OFF
Qualify_owners ON, OFF OFF
Quote_all_identifiers ON, OFF OFF
Replication_error procedure-name NULL
Save_remote_passwords ON, OFF ON
SR_Date_Format date-string yyyy/mm/dd
SR_Time_Format time-string hh:nn:ss.Ssssss
SR_Timestamp_Format timestamp-string yyyy/mm/dd
hh:nn:ss.Ssssss
Subscribe_by_remote ON,OFF ON
Verify_threshold integer 256
Verify_all_columns ON,OFF OFF

These options are used by the Message Agent, and should be set for the user
ID specified on the Message Agent command line. They can also be set for
general public use.
The options are as follows:

542
Chapter 22 Utilities and Options Reference

Blob_threshold option Any value longer than the Blob_threshold option


is replicated as a blob. That is, it is broken into pieces and replicated in
chunks, before being reconstituted by using a SQL variable and
concatenating the pieces at the recipient site.
If you are replicating blobs in an installation with Adaptive Server
Enterprise, you must ensure that Blob_threshold is set to a value larger the
largest blob being replicated.
$ For information on blob replication and Adaptive Server Enterprise, see
"Replication of blobs" on page 307.

Compression option Set the level of compression for messages. Values


can be from -1 to 9, and have the following meanings:
♦ -1 Send messages in Version 5 format. Message Agents (both
dbremote and ssremote) from previous versions of SQL Remote cannot
read messages sent in Version 6 format. You should ensure that
COMPRESSION is set to -1 until all Message Agents in your system are
upgraded to Version 6.
♦ 0 No compression.
♦ 1 to 9 Increasing degrees of compression. Creating messages with
high compression can take longer than creating messages with low
compression.

Delete_old_logs option This option is used by SQL Remote and by the


Adaptive Server Anywhere Replication Agent. The default setting is OFF.
When set to ON, the Message Agent (DBREMOTE) deletes each old
transaction log when all the changes it contains have been sent and
confirmed as received.

External_remote_options This option is used by SQL Remote to


indicate whether the message link parameters should be stored in the
database (OFF) or externally (ON). By default, the setting is OFF.

Qualify_owners option Controls whether SQL statements being


replicated by SQL Remote should use qualified object names. The default in
Adaptive Server Anywhere is ON and the default in Adaptive Server
Enterprise is OFF.
Qualifying owners in Adaptive Server Enterprise setups is rarely needed
because it is common for objects to be owned by dbo. When qualification is
not needed in Adaptive Server Anywhere setups, messages will be slightly
smaller with the option off.

Quote_all_identifiers option Controls whether SQL statements being


replicated by SQL Remote should use quoted identifiers. The default is OFF.

543
SQL Remote options

When this option is off, the dbremote quotes identifiers that require quotes
by Adaptive Server Anywhere (as it has always done) and ssremote does not
quote any identifiers. When the option is on, all identifiers are quoted.

Replication_error option Specifies a stored procedure called by the


Message Agent when a SQL error occurs. By default no procedure is called.
The replication error procedure must have a single argument of type CHAR,
VARCHAR, or LONG VARCHAR. The procedure may be called once with
the SQL error message and once with the SQL statement that causes the
error.
While the option allows you to track and monitor SQL errors in replication,
you must still design them out of your setup: this option is not intended to
resolve such errors.
You can use a table with DEFAULT CURRENT REMOTE USER to record
the remote site that caused the error.

Save_remote_passwords option When a password is entered into the


message link dialog box on first connection, the parameter values are saved.
By default, Save_remote_passwords is ON and the password is saved. If you
are storing the message link parameters externally, rather than in the
database, you may wish not to save the passwords. You can prevent the
passwords from being saved by setting this option to NO.

SR_Date_Format option The Message Agent uses this option when


replicating columns that store a date. The option is a string build from the
following symbols:

Symbol Description
yy Two digit year
yyyy Four-digit year
mm Two-digit month
mmm Character format for month
dd Two-digit day

Each symbol is substituted with the date being replicated.


If you set the mm format symbol in upper case, the corresponding characters
are also upper case.
For the digit formats, the case of the option setting controls padding. If the
symbols are the same case (such as DD), the number is padded with zeroes.
If the symbols are mixed case (such as Mm), the number is not zero padded.

544
Chapter 22 Utilities and Options Reference

SR_Time_Format option The Message Agent uses this option when


replicating columns that store a time. The option is a string build from the
following symbols:

Symbol Description
hh Two digit hours (24-hour clock)
nn Two-digit minutes
mm Two digit minutes if following a
colon (as in hh:mm)
ss[.s...] Two-digit seconds plus optional
fractions of a second.

Using mixed case in the formatting string suppresses leading zeroes.

SR_Timestamp_Format The Message Agent replicates datetime


information using this option. For Adaptive Server Anywhere this is the
timestamp, datetime, and smalldatetime data types. For Adaptive Server
Enterprise, this is the datetime and smalldatetime data types.
The format strings are taken from the SR_Date_Format and
SR_Time_Format settings.
The default setting is the SR_Date_Format setting,followed by the
SR_Time_Format setting.

Subscribe_by_remote option When set to ON, operations from remote


databases on rows with a subscribe by value that is NULL or an empty string
assume the remote user is subscribed to the row. When set to OFF, the
remote user is assumed not to be subscribed to the row.
The only limitation of this option is that it will lead to errors if a remote user
really does want to INSERT (or UPDATE) a row with a NULL or empty
subscription expression (for information held only at the consolidated
database). This is reasonably obscure and can be worked around by assigning
a subscription value in your installation that belongs to no remote user.
$ For more information about this option, see "Using the
Subscribe_by_remote option with many-to-many relationships" on page 345,
and "Using the Subscribe_by_remote option with many-to-many
relationships" on page 393.

Verify_threshold option If the data type of a column is longer than the


threshold, old values for the column are not verified when an UPDATE is
replicated. The default setting is 1000.
This option keeps the size of SQL Remote messages down, but has the
disadvantage that conflicting updates of long values are not detected.

545
SQL Remote options

Verify_all_columns option The default setting is OFF. When set to ON,


messages containing updates published by the local database are sent with all
column values included, and a conflict in any column triggers a RESOLVE
UPDATE trigger at the subscriber database.
The extraction utility for Adaptive Server Enterprise sets the public option in
remote Adaptive Server Anywhere databases to match the setting in the
Adaptive Server Enterprise database.
Examples ♦ The following statement sets the Verify_all_columns option to OFF in
Adaptive Server Anywhere, for all users:
SET OPTION PUBLIC.Verify_all_columns = ’OFF’
♦ The following statements set the Verify_all_columns option to OFF in
Adaptive Server Enterprise:
exec sp_remote_option Verify_all_columns, ’OFF’
go
In Adaptive Server Enterprise, replication options are used only by
SQL Remote.

546
C H A P T E R 2 3

System Objects for Adaptive Server


Anywhere

About this chapter SQL Remote-specific system information is held in a the Adaptive Server
Anywhere catalog. A more comprehensible version of this information is
held in a set of system views.
Contents
Topic Page
SQL Remote system tables 548
SQL Remote system views 554

547
SQL Remote system tables

SQL Remote system tables


This section describes the system tables used by SQL Remote to define and
manage SQL Remote information. In the following diagram, arrows indicate
foreign key relations between tables: the arrow leads from the foreign table
to the primary table.

SYSSUBSCRIPTION
publication_id <pk,fk> smallint
user_id <pk,fk> smallint user_id = user_id
subscribe_by <pk> char(128)
created numeric(20,0)
started numeric(20,0)
SYSREMOTEUSER
publication_id = publication_id user_id <pk> smallint
consolidate char(1)
type_id <fk> smallint
SYSPUBLICATION address long varchar
frequency char(1)
publication_id <pk> smallint
send_time time
publication_name char(128)
log_send numeric(20,0)
remarks long varchar
time_sent timestamp
log_sent numeric(20,0)
confirm_sent numeric(20,0)
publication_id = publication_id send_count integer
resend_count integer
SYSARTICLE time_received timestamp
publication_id <pk,fk> smallint log_received numeric(20,0)
table_id <pk> smallint confirm_received numeric(20,0)
where_expr long varchar receive_count integer
subscribe_by_expr long varchar rereceive_count integer
query char(1)

type_id = type_id
publication_id = publication_id
table_id = table_id
SYSREMOTETYPE
SYSARTICLECOL type_id <pk> smallint
publication_id <pk,fk> smallint type_name char(128)
table_id <pk,fk> smallint publisher_address long varchar
column_id <pk> smallint remarks long varchar

These tables are described in more detail in the following sections.

SYSARTICLE table
Function Each row describes an article in a SQL Remote publication.

548
Chapter 23 System Objects for Adaptive Server Anywhere

Columns Column Data type Description


publication_id UNSIGNED INT The publication of which this article is a
part.
table_id UNSIGNED INT Each article consists of columns and
rows from a single table. This column
contains the table ID for this table.
where_expr LONG VARCHA For articles that contain a subset of rows
R defined by a WHERE clause, this
column contains the search condition.
subscribe_by_expr LONG VARCHA For articles that contain a subset of rows
R defined by a SUBSCRIBE BY
expression, this column contains the
expression.
query CHAR(1) The SUBSCRIBE BY expression could
be a subquery that returns multiple
values. This column contains Y or N to
indicate if the expression is a subquery
(Y) or not (N). This column is used by
the Extraction utility

SYSARTICLECOL table
Function Each row identifies a column in an article, identifying the column, the table it
is in, and the publication it is part of.
Columns Column Data type Description
publication_id UNSIGNED IN A unique identifier for the publication of
T which the column is a part.
table_id UNSIGNED IN The table to which the column belongs.
T
column_id UNSIGNED IN The column identifier, from the
T SYSCOLUMN system table.

SYSPUBLICATION table
Function Each row describes a SQL Remote publication.

549
SQL Remote system tables

Columns Column Data type Description


publication_id UNSIGNED INT A unique identifier for the publication
creator UNSIGNED INT The user ID that owns the publication
publication_name VARCHAR(128) The name of the publication
remarks LONG VARCHA Comments
R

SYSREMOTEOPTION table
Function Each row describes the values of a SQL Remote message link parameter.
Columns Column Data type Description
option_id UNSIGNED INT An identification number for the
message link parameter.
user_id UNSIGNED INT The user ID for which the parameter is
set.
"setting00" VARCHAR(255) The value of the message link
parameter.

SYSREMOTEOPTIONTYPE table
Function Each row describes one of the SQL Remote message link parameters.
Columns Column Data type Description
option_id UNSIGNED INT An identification number for the
message link parameter.
type_id SMALLINT An identification number for the
message type that uses this parameter

"option" VARCHAR(128) The name of the message link


parameter.

SYSREMOTETYPE table
Function Each row describes one of the SQL Remote message types, including the
publisher address.

550
Chapter 23 System Objects for Adaptive Server Anywhere

Columns Column Data type Description


type_id SMALLINT An identification number for the
message type.
type_name VARCHAR(128) The message type. There is a separate
row for each of the following:
♦ FILE
♦ MAPI
♦ VIM
♦ SMTP
publisher_address VARCHAR(128) The publisher’s address for the message
type type_name. SQL Remote receives
messages from this address.
remarks LONG VARCHA Comments
R

SYSREMOTEUSER table
Function Each row describes a user ID with REMOTE permissions (a subscriber),
together with the status of SQL Remote messages sent to and from that user.
Columns Column Data type Description
user_id UNSIGNED INT The user ID of the user with REMOTE
permissions.
consolidate CHAR(1) The column contains either an N to
indicate a user granted REMOTE
permissions, or a Y to indicate a user
granted CONSOLIDATE permissions.
type_id SMALLINT The ID of the message system used to
send messages to this user.
address LONG VARCHA The address to which SQL Remote
R messages are to be sent. The address
must be appropriate for the
address_type.
frequency CHAR(1) How frequently SQL Remote messages
are to be sent. P for Periodically, and A
stands for Occasionally.
send_time TIME The next time messages are to be sent
to this user.

551
SQL Remote system tables

Column Data type Description


log_send NUMERIC(20, 0) If log_send is greater than log_sent,
the Message Agent resends messages
immediately to the subscriber the next
time it is run.
time_sent TIMESTAMP The time the most recent message was
sent to this subscriber.
log_sent NUMERIC(20, 0) The local log offset for the most
recently sent operation to this
subscriber.
confirm_sent NUMERIC(20, 0) The log offset for the most recently
confirmed operation from this
subscriber.
send_count INT The number of SQL Remote messages
have been sent to this subscriber.
resend_count INT Counter to ensure messages are applied
only once at the subscriber database.
time_received DATETIME The time the most recent message was
received from this subscriber.
log_received NUMERIC(20, 0) The log offset in the subscriber’s
database for the operation most
recently received at the current
database.
confirm_received NUMERIC(20, 0) The log offset in the subscriber’s
database for the most recent operation
for which a confirmation message has
been sent.
receive_count INT How number of messages received
from this subscriber.
rereceive_count INT Counter to ensure messages are applied
only once at the current database.

SYSSUBSCRIPTION table
Function Each row describes a subscription from one user ID (which must have
REMOTE permissions) to one publication.

552
Chapter 23 System Objects for Adaptive Server Anywhere

Columns Column Data type Description


publication_id UNSIGNED INT The identifier for the publication to which
the user ID is subscribed.
user_id UNSIGNED INT The user ID that is subscribed to the
publication.
subscribe_by VARCHAR(128) For publications with a SUBSCRIBE BY
expression, this column holds the matching
value for this subscription.
created NUMERIC(20, 0) The offset in the transaction log at which the
subscription was created.
started NUMERIC(20, 0) The offset in the transaction log at which the
subscription was started.

553
SQL Remote system views

SQL Remote system views


This section describes the database views used by SQL Remote to present
and summarize SQL Remote information.

SYSARTICLES view
Function Each row lists describes an article.
Columns Column Description
publication_name The publication of which this article is a part.
table_name Each article consists of columns and rows from a
single table. This column contains the name of this
table.
where_expr For articles that contain a subset of rows defined by
a WHERE clause, this column contains the search
condition.
subscribe_by_expr For articles that contain a subset of rows defined by
a SUBSCRIBE BY expression, this column
contains the expression.

SYSARTICLECOLS view
Function Each row describes a column that appears in an article.
Columns Column Description
publication_name The name of the publication of which the column is
a part.
table_name The name of the table to which the column belongs.
column_name The column name.

SYSPUBLICATIONS view
Function Lists the names of all publications.

554
Chapter 23 System Objects for Adaptive Server Anywhere

Columns Column Description


publication_name The name of the publication
createor The owner of the publication
remarks Comments

SYSREMOTEOPTIONS view
Function Lists the SQL Remote message link parameters and their values, as stored in
the SYSREMOTEOPTION and SYSREMOTEOPTIONTYPE system tables, in
more readable form.
Columns Column Description
type_name The message link type.
"option" The option name.
setting The option value.

SYSREMOTEUSERS view
Function Lists information about remote users and their status.
Columns Column Description
user_name The user ID of the user with REMOTE permissions.
consolidate The column contains either an N to indicate a user
with REMOTE permissions, or a Y to indicate a user
with CONSOLIDATE permissions.
type_name The name of the message type used to send messages
to this user.
address The address to which SQL Remote messages are to
be sent. The address must be appropriate for the
address_type.
frequency How frequently SQL Remote messages are to be sent.
send_time The next time messages are to be sent to this user.
next_send The next time messages are to be sent to this user, in
a more comprehensible format.
log_send Messages are sent only to subscribers for whom
log_send is greater than log_sent.

555
SQL Remote system views

Column Description
time_sent The time the most recent message was sent to this
subscriber.
log_sent The transaction log offset for the most recently sent
operation.
confirm_sent The transaction log offset for the most recently
confirmed operation from this subscriber.
send_count How many SQL Remote messages have been sent.
resend_count Counter to ensure messages are applied only once at
the subscriber database.
time_received The time the most recent message was received from
this subscriber.
log_received The log offset in the subscriber’s database for the
operation most recently received at the current
database.
confirm_received The log offset in the subscriber’s database for the
most recent operation for which a confirmation
message has been sent.
receive_count How many messages have been received.
rereceive_count Counter to ensure messages are applied only once at
the current database.

SYSSUBSCRIPTIONS view
Function Each row lists information about a subscription.
Columns Column Description
publication_name The name of the publication to which the user ID is
subscribed.
user_name The user ID that is subscribed to the publication.
subscribe_by For publications with a SUBSCRIBE BY
expression, this column holds the matching value
for this subscription.
created The offset in the transaction log at which the
subscription was created.
started The offset in the transaction log at which the
subscription was started.

556
C H A P T E R 2 4

System Objects for Adaptive Server


Enterprise

About this chapter SQL Remote-specific system information is held in a set of tables called the
SQL Remote system tables. A more comprehensible version of this
information is held in a set of views, called the SQL Remote system views.
Contents
Topic Page
SQL Remote system tables 558
SQL Remote system views 566
Stable Queue tables 570

557
SQL Remote system tables

SQL Remote system tables


This section describes the database tables used by SQL Remote to define and
manage SQL Remote information.

Caution
These tables are for use only by SQL Remote. Do not alter these tables or
their contents directly.

#remote table
Function This temporary table is created by the Message Agent to hold the name of
the current remote user and of the current publisher. This table exists only in
Adaptive Server Enterprise.
Columns Column Data type Description
current_remote_user VARCHAR(128) Current remote user (from the
Message Agent command line).
current_publisher VARCHAR(128) Current publisher

Description This is not a system table. When the Message Agent for Adaptive Server
Enterprise connects to the server, it holds the value of the current remote user
ID and the value of the current publisher in the #remote table. This
temporary table is held in TEMPDB.
The values from #remote can be used in conflict resolution procedures.
The CREATE TABLE statement for this table is:
CREATE TABLE #remote (
current_remote_user varchar(128),
current_publisher varhcar(128)
)
The table has a single row.

sr_article table
Function Each row describes an article in a SQL Remote publication.

558
Chapter 24 System Objects for Adaptive Server Enterprise

Columns Column Data type Description


publication_id INT The publication of which this article is
a part.
table_id INT Each article consists of columns and
rows from a single table. This column
contains the table ID for this table.
where_expr VARCHAR(128) For articles that contain a subset of
rows defined by a WHERE clause, this
column contains the search condition.
subscribe_by_expr VARCHAR(128) For articles that contain a subset of
rows defined by a SUBSCRIBE BY
expression, this column contains the
expression.
subscribe_by_view VARCHAR(128) For articles that contain a subset of the
rows defined by a view. This column
contains the name of the view.

sr_articlecol table
Function Each row identifies a column in an article, identifying the column, the table it
is in, and the publication it is part of.
Columns Column Data type Description
publication_id INT A unique identifier for the publication of
which the column is a part.
table_id INT The table to which the column belongs.
column_id INT The column identifier, from the
SYSCOLUMN system table.

sr_marker table
Function To ensure that messages received by the Message Agent are sent to remote
databases in the same session
Columns Column Data type Description
marker DATETIME A time value indicating when the
latest messages were applied.

559
SQL Remote system tables

When a consolidated database uses two Message Agents, one to populate the
Description
stable queue (-i) and one to receive and send messages (-r -s), the single row
of the sr_marker table is used to ensure that messages received and applied
to the database are sent before the Message Agent closes down.

sr_object table
Function Holds a list of SQL Remote objects. The extraction utility needs to know not
to extract the SQL Remote system objects. The sp_populate_sql_anywhere
procedure that creates a set of Adaptive Server Anywhere system tables in
TEMPDB gets a list of SQL Remote objects from the sr_object table.
Columns Column Data type Description
name VARCHAR(128) The name of the object.
type CHAR(1) One of the following:
♦ U User-defined table
♦ V View
♦ P Procedure

sr_option table
Function Each row describes a replication option used by SQL Remote.
Columns Column Data type Description
option VARCHAR(128) The name of the option.
value VARCHAR(128) The setting for the option.

Description $ For information about available options, see "SQL Remote options" on
page 542.

sr_passthrough table
Function Each row describes a passthrough operation being sent to a user or to
subscribers to a publication.

560
Chapter 24 System Objects for Adaptive Server Enterprise

Columns Column Data type Description


operation VARCHAR(20) A passthrough operation, or piece of a
passthrough operation, entered using
sp_passthrough or sp_passthrough_piece.
value VARCHAR(255) A subscription column value indicating which
users are to receive the operation.
id INT A user who is to receive the operation.

sr_publication table
Function Each row describes a SQL Remote publication.
Columns Column Data type Description
publication_id INT An identifier for the publication
publication_name VARCHAR(128) The name of the publication.

sr_publisher table
Function The row holds the user ID of the publisher.
Columns Column Data type Description
user_id INT The user ID of the publisher.

sr_remoteoption table
Function Each row describes the values of a SQL Remote message link parameter.
Columns Column Data type Description
option_id INTEGER An identification number for the
message link parameter.
user_id INTEGER The user ID for which the parameter is
set.
"setting00" VARCHAR(255) The value of the message link
parameter.

561
SQL Remote system tables

sr_remoteoptiontype table
Function Each row describes one of the SQL Remote message link parameters.
Columns Column Data type Description
option_id INTEGER An identification number for the
message link parameter.
type_id INTEGER An identification number for the
message type that uses this parameter

"option" VARCHAR(128) The name of the message link


parameter.

sr_remotetable table
Function Each row describes a table that is marked for replication using SQL Remote.
Columns Column Data type Description
table_id INT The id of the table.
resolve_name VARCHAR(128) The name of the stored procedure to be
executed in the case of conflicts.
old_row_name VARCHAR(128) The table that holds the old row name.
remote_row_name VARCHAR(128) The table that holds the remote row
name.

sr_remotetype table
Function Each row describes one of the SQL Remote message types, including the
publisher address.

562
Chapter 24 System Objects for Adaptive Server Enterprise

Columns Column Data type Description


type_id INT An identification number for the
message type.
type_name VARCHAR(128) The message type. There is a separate
row for each of the following:
♦ FILE
♦ MAPI
♦ VIM
♦ SMTP
publisher_address VARCHAR(128) The publisher’s address for the message
type type_name.

sr_remoteuser table
Function Each row describes a user ID with REMOTE permissions (a subscriber),
together with the status of SQL Remote messages sent to and from that user.
Columns Column Data type Description
user_id INT The user ID of the user with REMOTE
permissions.
consolidate CHAR(1) The column contains either an N to
indicate a user granted REMOTE
permissions, or a Y to indicate a user
granted CONSOLIDATE permissions.
type_id INT The ID of the message system used to
send messages to this user.
address VARCHAR(128) The address to which SQL Remote
messages are to be sent. The address
must be appropriate for the
address_type.
frequency CHAR(1) How frequently SQL Remote messages
are to be sent.
send_time DATETIME The next time messages are to be sent to
this user.
log_send NUMERIC(20, 0) Messages are sent only to subscribers for
whom log_send is greater than log_sent.
time_sent DATETIME The time the most recent message was
sent to this subscriber.

563
SQL Remote system tables

Column Data type Description


log_sent NUMERIC(20, 0) The log offset for the most recently sent
operation.
confirm_sent NUMERIC(20, 0) The log offset for the most recently
confirmed operation from this
subscriber.
send_count INT How many SQL Remote messages have
been sent.
resend_count INT Counter to ensure messages are applied
only once at the subscriber database.
time_received DATETIME The time the most recent message was
received from this subscriber.
log_received NUMERIC(20, 0) The log offset in the subscriber’s
database for the operation most recently
received at the current database.
confirm_received NUMERIC(20, 0) The log offset in the subscriber’s
database for the most recent operation
for which a confirmation message has
been sent.
receive_count INT How many messages have been received
from this subscriber.
rereceive_count INT Counter to ensure messages are applied
only once at the current database.
filler1 CHAR(255) Reserved
filler2 CHAR(255) Reserved
filler3 CHAR(255) Reserved
filler4 CHAR(255) Reserved

sr_subscription table
Function Each row describes a subscription from one user ID (which must have
REMOTE permissions) to one publication.

564
Chapter 24 System Objects for Adaptive Server Enterprise

Columns Column Data type Description


publication_id INT The identifier for the publication to which
the user ID is subscribed.
user_id INT The user ID that is subscribed to the
publication.
subscribe_by VARCHAR(128) For publications with a SUBSCRIBE BY
expression, this column holds the matching
value for this subscription.
created NUMERIC(20, 0) The offset in the transaction log at which the
subscription was created.
started NUMERIC(20, 0) The offset in the transaction log at which the
subscription was started.
operation VARCHAR(20)

565
SQL Remote system views

SQL Remote system views


This section describes the database views used by SQL Remote to present
and summarize SQL Remote information.

sr_articles view
Function Each row lists describes an article.
Columns Column Description
publication_name The publication of which this article is a part.
table_name Each article consists of columns and rows from a
single table. This column contains the name of this
table.
where_expr For articles that contain a subset of rows defined by
a WHERE clause, this column contains the search
condition.
subscribe_by_expr For articles that contain a subset of rows defined by
a SUBSCRIBE BY expression, this column contains
the expression.
subscribe_by_view For articles that contain a subset of rows defined by
a view, this column contains the name of the view.

sr_articlecols view
Function Each row describes a column that appears in an article.
Columns Column Description
publication_name The name of the publication of which the column is a
part.
table_name The name of the table to which the column belongs.
column_name The column name.

sr_publications view
Function Lists the names of all publications.

566
Chapter 24 System Objects for Adaptive Server Enterprise

Columns Column Description


publication_name The name of the publication

sr_remoteoptions view
Function Lists the SQL Remote message link parameters and their values, as stored in
the remoteoption and remoteoptiontype system tables, in more readable form.
Columns Column Description
type_name The message link type.
"option" The option name.
setting The option value.

sr_remotetables view
Function Lists the tables marked for SQL Remote replication, as stored in the
remotetable system table, in more readable form.
This table exists only in Adaptive Server Enterprise.
Columns Column Description
table_name The name of the table.
resolve_name The name of the stored procedure to be executed in
the case of conflicts.
old_row_name The table that holds the old row name.
remote_row_name The table that holds the remote row name.

sr_remotetypes view
Function Lists the message types, as stored in the remotetype system table.

567
SQL Remote system views

Columns Column Description


type_id An identification number for the message type.
type_name The message type. There is a separate row for each
of the following:
♦ FILE
♦ MAPI
♦ VIM
♦ SMTP
publisher_address The publisher’s address for the message type
type_name.

sr_remoteusers view
Function Lists information about remote users and their status.
Columns Column Description
user_name The user ID of the user with REMOTE permissions.
consolidate The column contains either an N to indicate a user
granted REMOTE permissions, or a Y to indicate a
user granted CONSOLIDATE permissions.
type_name The name of the message system used to send
messages to this user.
address The address to which SQL Remote messages are to
be sent. The address must be appropriate for the
address_type.
frequency How frequently SQL Remote messages are to be sent.
send_time The next time messages are to be sent to this user.
next_send The next time messages are to be sent to this user, in
a more comprehensible format.
log_send Messages are sent only to subscribers for whom
log_send is greater than log_sent.
time_sent The time the most recent message was sent to this
subscriber.
log_sent The log offset for the most recently sent operation.
confirm_sent The log offset for the most recently confirmed
operation from this subscriber.

568
Chapter 24 System Objects for Adaptive Server Enterprise

Column Description
send_count How many SQL Remote messages have been sent.
resend_count Counter to ensure messages are applied only once at
the subscriber database.
time_received The time the most recent message was received from
this subscriber.
log_received The log offset in the subscriber’s database for the
operation most recently received at the current
database.
confirm_received The log offset in the subscriber’s database for the
most recent operation for which a confirmation
message has been sent.
receive_count How many messages have been received.
rereceive_count Counter to ensure messages are applied only once at
the current database.

sr_subscriptions view
Function Each row lists information about a subscription.
Columns Column Description
publication_name The name of the publication to which the user ID is
subscribed.
user_name The user ID that is subscribed to the publication.
subscribe_by For publications with a SUBSCRIBE BY expression,
this column holds the matching value for this
subscription.
created The offset in the transaction log at which the
subscription was created.
started The offset in the transaction log at which the
subscription was started.

569
Stable Queue tables

Stable Queue tables


This section describes the database tables used by SQL Remote to define and
manage the stable queue information. The stable queue may be kept in the
same database as the SQL Remote database, or in a separate database.
The stable queue is used only by SQL Remote for Adaptive Server
Enterprise.

sr_queue_state table
Function A single row table that stores persistent global information about the state of
the stable queue.

570
Chapter 24 System Objects for Adaptive Server Enterprise

Columns Column Data type Description


version INT The stable queue version number
page_id INT Transaction log page_id of the last
entry scanned.
row_id INT Transaction log row_id of the last
entry scanned.
confirm_offset NUMERIC(20,0) The minimum value of the
confirmation offsets received from
all remote users. This value is used
by the Message Agent to decide
which transactions can be deleted
from the stable queue.
commit_offset NUMERIC(20,0) The transaction log offset of the
most recent transaction completed
before the oldest incomplete
transaction.
backup_offset NUMERIC(20,0) The transaction log offset of the last
dump database or dump
transaction command.
This information is used when the
Message Agent is run with the -u
command-line switch (replicate only
backed up transactions).
marker DATETIME The most recent incoming message
that has been scanned into the stable
queue. When a message is applied to
the Adaptive Server Enterprise
server, it sets the time_received
column in sr_remoteuser. When the
transaction log is scanned and the
transactions from that message are
scanned into the stable queue, it sets
the time_received column of
sr_queue_state.
The purpose of the column is co-
ordination between one Message
Agent that is scanning the
transaction log continuously and
another Message Agent that is
receiving messages and sending
messages in batch mode. When in
batch mode, the Message Agent
receives messages, waits for those
messages to be scanned into the
stable queue, and then sends

571
Stable Queue tables

Column Data type Description


messages. The waiting is done
through the database by looking at
the time_received column of
sr_queue_state.
confirmed_id NUMERIC(20,0) The sending thread deletes rows
with confirmed_id less than this
value from
sr_confirmed_transaction.

sr_transaction table
Function This table has one row for each transaction in the stable queue.
Columns Column Description
offset The transaction log offset of the commit operation for the
transaction. This value uniquely identifies each transaction
user_id The remote user where the transaction originated. This column
holds NULL if the transaction did not originate from a remote
user.
The user_id column is used to ensure that actions are not
replicated back to the remote site that entered them.
data The transaction itself, in an internal representation.

572
Chapter 24 System Objects for Adaptive Server Enterprise

sr_confirmed_transaction table
Function Each row marks the corresponding row in sr_transaction.
Columns Column Data type Description
confirmed_id NUMERIC (20,0) A unique ID
offset NUMERIC (20,0) A copy of an offset used to mark rows
in sr_transaction for deletion.

sr_queue_coordinate table
Function A single row, that coordinates the SQL Remote log scanning thread and the
sending thread to access the stable queue and related tables.
Columns Column Data type Description
status CHAR(1) N if the stable queue has not yet been used
by SQL Remote. L and S if the SQL Remote
log scanning thread and sending thread have
accessed the queue.

573
Stable Queue tables

574
C H A P T E R 2 5

Command Reference for Adaptive Server


Anywhere

About this chapter This chapter describes the SQL statements used for executing SQL Remote
commands, and the system tables, used for storing information about the
SQL Remote installation and its state.
Contents
Topic Page
ALTER PUBLICATION statement 577
ALTER REMOTE MESSAGE TYPE statement 578
CREATE PUBLICATION statement 579
CREATE REMOTE MESSAGE TYPE statement 581
CREATE SUBSCRIPTION statement 583
CREATE TRIGGER statement 584
DROP PUBLICATION statement 587
DROP REMOTE MESSAGE TYPE statement 588
DROP SUBSCRIPTION statement 589
GRANT CONSOLIDATE statement 590
GRANT PUBLISH statement 592
GRANT REMOTE statement 593
GRANT REMOTE DBA statement 595
PASSTHROUGH statement 596
REMOTE RESET statement 597
REVOKE CONSOLIDATE statement 598
REVOKE PUBLISH statement 599
REVOKE REMOTE statement 600
REVOKE REMOTE DBA statement 601
SET REMOTE OPTION statement 602

575
ALTER PUBLICATION statement

START SUBSCRIPTION statement 604


STOP SUBSCRIPTION statement 606
SYNCHRONIZE SUBSCRIPTION statement 607
UPDATE statement 608

576
Chapter 25 Command Reference for Adaptive Server Anywhere

ALTER PUBLICATION statement


Function Use this statement to alter the definition of a SQL Remote publication.
Syntax ALTER PUBLICATION [ owner.]publication-name
ADD TABLE article-description
… | MODIFY TABLE article-description
| { DELETE | DROP } TABLE [ owner.]table-name
| RENAME publication-name
Parameters article-description:
table-name [ ( column-name, … ) ]
… [ WHERE search-condition ]
… [ SUBSCRIBE BY expression ]
Usage Anywhere. This statement is applicable only to SQL Remote.
Permissions Must have DBA authority, or be owner of the publication. Requires
exclusive access to all tables referred to in the statement.
Side effects Automatic commit.
See also "CREATE PUBLICATION statement" on page 579
"DROP PUBLICATION statement" on page 587
"sp_add_article procedure" on page 613
"sp_add_article_col procedure" on page 615
Description The ALTER PUBLICATION statement alters a SQL Remote publication in
the database. The contribution to a publication from one table is called an
article. Changes can be made to a publication by adding, modifying, or
deleting articles, or by renaming the publication. If an article is modified, the
entire specification of the modified article must be entered.
Example The following statement adds the customer table to the pub_contact
publication.
ALTER PUBLICATION pub_contact (
ADD TABLE customer
)

577
ALTER REMOTE MESSAGE TYPE statement

ALTER REMOTE MESSAGE TYPE statement


Function Use this statement to change the publisher’s message system, or the
publisher’s address for a given message system, for a message type that has
been created.
Syntax ALTER REMOTE MESSAGE TYPE message-system
.. ADDRESS address-string
Parameters Parameter Description
message-system One of the message systems supported by SQL Remote. It
must be one of the following values:
♦ FILE
♦ FTP
♦ MAPI
♦ SMTP
♦ VIM
address-string A string containing a valid address for the specified message
system.

Permissions Must have DBA authority.


Side effects Automatic commit.
See also "CREATE REMOTE MESSAGE TYPE statement" on page 581
"sp_remote_type procedure" on page 656
Description The statement changes the publisher’s address for a given message type.
The Message Agent sends outgoing messages from a database by one of the
supported message links. The extraction utility uses this address when
executing the GRANT CONSOLIDATE statement in the remote database.
The address is the publisher’s address under the specified message system. If
it is an e-mail system, the address string must be a valid e-mail address. If it
is a file-sharing system, the address string is a subdirectory of the directory
specified by the SQLREMOTE environment variable, or of the current
directory if that is not set. You can override this setting on the GRANT
CONSOLIDATE statement at the remote database.
Example The following statement changes the publisher’s address for the FILE
message link to new_addr.
CREATE REMOTE MESSAGE TYPE file
ADDRESS ’new_addr’

578
Chapter 25 Command Reference for Adaptive Server Anywhere

CREATE PUBLICATION statement


Function Use this statement to create a publication for replication with SQL Remote.
Syntax CREATE PUBLICATION [ owner.]publication-name
… ( TABLE article-description, … )
Parameters article-description:
table-name [ ( column-name, … ) ]
… [ WHERE search-condition ]
… [ SUBSCRIBE BY expression ]
Permissions Must have DBA authority. Requires exclusive access to all tables referred to
in the statement.
Side effects Automatic commit.
See also "ALTER PUBLICATION statement" on page 577
"DROP PUBLICATION statement" on page 587
"sp_create_publication procedure" on page 618
Description The CREATE PUBLICATION statement creates a publication in the
database. A publication can be created for another user by specifying an
owner name.
In SQL Remote, publishing is a two-way operation, as data can be entered at
both consolidated and remote databases. In a SQL Remote installation, any
consolidated database and all remote databases must have the same
publication defined. Running the extraction utility from a consolidated
database automatically executes the correct CREATE PUBLICATION
statement in the remote database.
Article Publications are built from articles. Each article is a table or part of a
table. An article may be a vertical partition of a table (a subset of the table’s
columns), a horizontal partition (a subset of the table’s rows) or a vertical and
horizontal partition.

SUBSCRIBE BY clause One way of defining a subset of rows of a table to


be included in an article is to use a SUBSCRIBE BY clause. This clause
allows many different subscribers to receive different rows from a table in a
single publication definition.

WHERE clause The WHERE clause is a way of defining the subset of rows
of a table to be included in an article. It is useful if the same subset is to be
received by all subscribers to the publication.
You can combine WHERE and SUBSCRIBE BY clauses in an article
definition.
Example The following statement creates a simple publication:

579
CREATE PUBLICATION statement

CREATE PUBLICATION pub_contact (


TABLE contact
)

580
Chapter 25 Command Reference for Adaptive Server Anywhere

CREATE REMOTE MESSAGE TYPE statement


Function Use this statement to identify a message-link and return address for outgoing
messages from a database.
Syntax CREATE REMOTE MESSAGE TYPE message-system
…ADDRESS address-string
Parameters Parameter Description
message-system One of the message systems supported by SQL Remote. It
must be one of the following values:
♦ FILE
♦ FTP
♦ MAPI
♦ SMTP
♦ VIM
address-string A string containing a valid address for the specified message
system.

Permissions Must have DBA authority.


Side effects Automatic commit.
See also "GRANT PUBLISH statement" on page 592
"GRANT REMOTE statement" on page 593
"GRANT CONSOLIDATE statement" on page 590
"sp_remote_type procedure" on page 656
"Using message types" on page 441
Description The Message Agent sends outgoing messages from a database using one of
the supported message links. Return messages for users employing the
specified link are sent to the specified address as long as the remote database
is created by the extraction utility. The Message Agent starts links only if it
has remote users for those links.
The address is the publisher’s address under the specified message system. If
it is an e-mail system, the address string must be a valid e-mail address. If it
is a file-sharing system, the address string is a subdirectory of the directory
set in the SQLREMOTE environment variable, or of the current directory if
that is not set. You can override this setting on the GRANT CONSOLIDATE
statement at the remote database.

581
CREATE REMOTE MESSAGE TYPE statement

The initialization utility creates message types automatically, without an


address. Unlike other CREATE statements, the CREATE REMOTE
MESSAGE TYPE statement does not give an error if the type exists; instead
it alters the type.
Example When remote databases are extracted using the extraction utility, the
following statement sets all recipients of file message-system messages to
send messages back to the company subdirectory.
The statement also instructs dbremote to look in the company subdirectory
for incoming messages.
CREATE REMOTE MESSAGE TYPE file
ADDRESS ’company’

582
Chapter 25 Command Reference for Adaptive Server Anywhere

CREATE SUBSCRIPTION statement


Function Use this statement to create a subscription for a user to a publication.
Syntax CREATE SUBSCRIPTION
… TO publication-name [ ( subscription-value ) ]
… FOR subscriber-id
Parameters Parameter Description
publication-name The name of the publication to which the user is being
subscribed. This may include the owner of the publication.
subscription-value A string that is compared to the subscription expression of
the publication. The subscriber receives all rows for which
the subscription expression matches the subscription value.
subscriber-id The user ID of the subscriber to the publication. This user
must have been granted REMOTE permissions.

Permissions Must have DBA authority.


Side effects Automatic commit.
See also "DROP SUBSCRIPTION statement" on page 589
"GRANT REMOTE statement" on page 593
"SYNCHRONIZE SUBSCRIPTION statement" on page 607
"START SUBSCRIPTION statement" on page 604
"sp_subscription procedure" on page 662
Description In a SQL Remote installation, data is organized into publications for
replication. In order to receive SQL Remote messages, a subscription must
be created for a user ID with REMOTE permissions.
If a string is supplied in the subscription, it is matched against each
SUBSCRIBE BY expression in the publication. The subscriber receives all
rows for which the value of the expression is equal to the supplied string.
In SQL Remote, publications and subscriptions are two-way relationships. If
you create a subscription for a remote user to a publication on a consolidated
database, you should also create a subscription for the consolidated database
on the remote database. The extraction utility carries this out automatically.
Example ♦ The following statement creates a subscription for the user p_chin to the
publication pub_sales. The subscriber receives all rows for which the
subscription expression has a value of Eastern.
CREATE SUBSCRIPTION
TO pub_sales ( ’Eastern’ )
FOR p_chin

583
CREATE TRIGGER statement

CREATE TRIGGER statement


Function Use this statement to create a new trigger in the database. One form of
trigger is designed specifically for use by SQL Remote.
Syntax CREATE TRIGGER trigger-name trigger-time trigger-event
[, trigger-event,..]
… [ ORDER integer ] ON table-name
… [ REFERENCING [ OLD AS old-name ]
[ NEW AS new-name ] ]
[ REMOTE AS remote-name ] ]
… [ FOR EACH { ROW | STATEMENT } ]
… [ WHEN ( search-condition ) ]
… [ IF UPDATE ( column-name ) THEN
… [ { AND | OR } UPDATE ( column-name ) ] … ]
… compound-statement
… [ ELSEIF UPDATE ( column-name ) THEN
… [ { AND | OR } UPDATE ( column-name ) ] …
… compound-statement
… END IF ] ]
Parameters trigger-time:
BEFORE | AFTER | RESOLVE
trigger-event:
DELETE | INSERT | UPDATE | UPDATE OF column-list
Usage Anywhere.
Permissions Must have RESOURCE authority and have ALTER permissions on the table,
or must have DBA authority. CREATE TRIGGER puts a table lock on the
table and thus requires exclusive use of the table.
Side effects Automatic commit.
See also "UPDATE statement" on page 608
Description The CREATE TRIGGER statement creates a trigger associated with a table
in the database and stores the trigger in the database.
Triggers can be triggered by one or more of the following events:
♦ INSERT Invoked whenever a new row is inserted into the table
associated with the trigger.
♦ DELETE Invoked whenever a row of the associated table is deleted.
♦ UPDATE Invoked whenever a row of the associated table is updated.
♦ UPDATE OF column-list Invoked whenever a row of the associated
table is updated and a column in the column-list has been modified.

584
Chapter 25 Command Reference for Adaptive Server Anywhere

BEFORE UPDATE triggers fire any time an update occurs on a row,


regardless of whether or not the new value differs from the old value.
AFTER UPDATE triggers will fire only if the new value is different from
the old value.
Row and The trigger is declared as either a row-level trigger, in which case it executes
statement-level before or after each row is modified, or as a statement-level trigger, in which
triggers case it executes after the entire triggering statement is completed.
Row-level triggers can be defined to execute BEFORE or AFTER the insert,
update, or delete. Statement-level triggers execute AFTER the statement.
The RESOLVE trigger time is for use with SQL Remote; it fires before row-
level UPDATE or UPDATE OF column-lists only.
To declare a trigger as a row-level trigger, use the FOR EACH ROW clause.
To declare a trigger as a statement-level trigger, you can either use a FOR
EACH STATEMENT clause or omit the FOR EACH clause. For clarity, it is
recommended that you enter the FOR EACH STATEMENT clause if
declaring a statement-level trigger.
Order of firing Triggers of the same type (insert, update, or delete) that fire at the same time
(before, after, or resolve) can use the ORDER clause to determine the order
that the triggers are fired.
Referencing The REFERENCING OLD and REFERENCING NEW clauses allow you to
deleted and refer to the deleted and inserted rows. For the purposes of this clause, an
inserted values UPDATE is treated as a delete followed by an insert.
The REFERENCING REMOTE clause is for use with SQL Remote. It
allows you to refer to the values in the VERIFY clause of an UPDATE
statement. It should be used only with RESOLVE UPDATE or RESOLVE
UPDATE OF column-list triggers.
The meaning of REFERENCING OLD and REFERENCING NEW differs,
depending on whether the trigger is a row-level or a statement-level trigger.
For row-level triggers, the REFERENCING OLD clause allows you to refer
to the values in a row prior to an update or delete, and the REFERENCING
NEW clause allows you to refer to the inserted or updated values. The OLD
and NEW rows can be referenced in BEFORE and AFTER triggers. The
REFERENCING NEW clause allows you to modify the new row in a
BEFORE trigger before the insert or update operation takes place.
For statement-level triggers, the REFERENCING OLD and
REFERENCING NEW clauses refer to declared temporary tables holding
the old and new values of the rows. The default names for these tables are
deleted and inserted.
The WHEN clause causes the trigger to fire only for rows where the search-
condition evaluates to true.

585
CREATE TRIGGER statement

Updating values BEFORE UPDATE triggers fire any time an UPDATE occurs on a row,
with the same whether or not the new value differs from the old value. AFTER UPDATE
value triggers fire only if the new value is different from the old value.
Example ♦ When a new department head is appointed, update the manager_id
column for employees in that department.
CREATE TRIGGER
tr_manager BEFORE UPDATE OF dept_head_id ON
department
REFERENCING OLD AS old_dept
NEW AS new_dept
FOR EACH ROW
BEGIN
UPDATE employee
SET employee.manager_id=new_dept.dept_head_id
WHERE employee.dept_id=old_dept.dept_id
END

586
Chapter 25 Command Reference for Adaptive Server Anywhere

DROP PUBLICATION statement


Function Use this statement to drop a SQL Remote publication.
Syntax DROP PUBLICATION [ owner.]publication-name
Usage Anywhere. This statement is applicable only to SQL Remote.
Permissions Must have DBA authority.
Side effects Automatic commit. All subscriptions to the publication are dropped.
See also "CREATE PUBLICATION statement" on page 579
"sp_drop_publication procedure" on page 619
Description The DROP PUBLICATION statement drops an existing publication from the
database.
Publication definitions are held at both consolidated and remote databases in
a SQL Remote installation.
Example DROP PUBLICATION pub_contact

587
DROP REMOTE MESSAGE TYPE statement

DROP REMOTE MESSAGE TYPE statement


Function Use this statement to delete a message type definition from a database.
Syntax DROP REMOTE MESSAGE TYPE message-system
Parameters Parameter Description
message-system One of the message systems supported by SQL Remote. It
must be one of the following values:
♦ FILE
♦ FTP
♦ MAPI
♦ SMTP
♦ VIM

Permissions Must have DBA authority. To be able to drop the type, there must be no user
granted REMOTE or CONSOLIDATE permissions with this type.
Side effects Automatic commit.
See also "CREATE REMOTE MESSAGE TYPE statement" on page 581
"ALTER REMOTE MESSAGE TYPE statement" on page 578
"sp_drop_remote_type procedure" on page 620
"Using message types" on page 441.
Description The statement removes a message type from a database.
Example The following statement drops the FILE message type from a database.
DROP REMOTE MESSAGE TYPE file

588
Chapter 25 Command Reference for Adaptive Server Anywhere

DROP SUBSCRIPTION statement


Function Use this statement to drop a subscription for a user from a publication.
Syntax DROP SUBSCRIPTION TO publication-name [ ( subscription-value ) ]
… FOR subscriber-id, …
Parameters Parameter Description
publication-name The name of the publication to which the user is being
subscribed. This may include the owner of the publication.
subscription-value A string that is compared to the subscription expression of
the publication. This value is required because a user may
have more than one subscription to a publication.
subscriber-id The user ID of the subscriber to the publication.

Permissions Must have DBA authority.


Side effects Automatic commit.
See also "CREATE SUBSCRIPTION statement" on page 583
"DROP SUBSCRIPTION statement" on page 589
Description Drops a SQL Remote subscription for a user ID to a publication in the
current database. The user ID will no longer receive updates when data in the
publication is changed.
In SQL Remote, publications and subscriptions are two-way relationships. If
you drop a subscription for a remote user to a publication on a consolidated
database, you should also drop the subscription for the consolidated database
on the remote database to prevent updates on the remote database being sent
to the consolidated database.
Example The following statement drops a subscription for the user ID SamS to the
publication pub_contact.
DROP SUBSCRIPTION TO pub_contact
FOR SamS

589
GRANT CONSOLIDATE statement

GRANT CONSOLIDATE statement


Function Use this statement to identify the database immediately above the current
database in a SQL Remote hierarchy, who will receive messages from the
current database.
Syntax GRANT CONSOLIDATE
… TO userid, …
… TYPE message-system, …
… ADDRESS address-string, …
… [ SEND { EVERY | AT }’hh:mm’ ]
Parameters Parameter Description
userid The user ID for the user to be granted the permission
message-system One of the message systems supported by SQL Remote. It
must be one of the following values:
♦ FILE
♦ FTP
♦ MAPI
♦ SMTP
♦ VIM
address-string A string containing a valid address for the specified message
system.

Permissions Must have DBA authority.


Side effects Automatic commit.
See also "GRANT REMOTE statement" on page 593
"REVOKE CONSOLIDATE statement" on page 598
"GRANT PUBLISH statement" on page 592
"sp_grant_consolidate procedure" on page 622
Description In a SQL Remote installation, the database immediately above the current
database in a SQL Remote hierarchy must be granted CONSOLIDATE
permissions. GRANT CONSOLIDATE is issued at a remote database to
identify its consolidated database. Each database can have only one user ID
with CONSOLIDATE permissions: you cannot have a database that is a
remote database for more than one consolidated database.
The consolidated user is identified by a message system, identifying the
method by which messages are sent to and received from the consolidated
user. The address-name must be a valid address for the message-system,
enclosed in single quotes.

590
Chapter 25 Command Reference for Adaptive Server Anywhere

For the FILE message type, the address is a subdirectory of the directory
pointed to by the SQLREMOTE environment variable.
The GRANT CONSOLIDATE statement is required for the consolidated
database to receive messages, but does not by itself subscribe the
consolidated database to any data. To subscribe to data, a subscription must
be created for the consolidated user ID to one of the publications in the
current database. Running the database extraction utility at a consolidated
database creates a remote database with the proper GRANT
CONSOLIDATE statement aready issued.
The optional SEND EVERY and SEND AT clauses specify a frequency at
which messages are sent. The string contains a time that is a length of time
between messages (for SEND EVERY) or a time of day at which messages
are sent (for SEND AT). With SEND AT, messages are sent once per day.
If a user has been granted remote permissions without a SEND EVERY or
SEND AT clause, the Message Agent processes messages, and then stops. In
order to run the Message Agent continuously, you must ensure that every
user with REMOTE permission has either a SEND AT or SEND EVERY
frequency specified.
It is anticipated that at many remote databases, the Message Agent will be
run periodically, and that the consolidated database will have no SEND
clause specified.
Example GRANT CONSOLIDATE TO con_db
TYPE mapi
ADDRESS ’Consolidated Database’

591
GRANT PUBLISH statement

GRANT PUBLISH statement


Function Use this statement to identify the publisher of the current database.
Syntax GRANT PUBLISH TO userid
Permissions Must have DBA authority.
Side effects Automatic commit.
See also "GRANT REMOTE statement" on page 593
"GRANT CONSOLIDATE statement" on page 590
"REVOKE PUBLISH statement" on page 599
"CREATE PUBLICATION statement" on page 579
"CREATE SUBSCRIPTION statement" on page 583
"sp_publisher procedure" on page 639
Description Each database in a SQL Remote installation is identified in outgoing
messages by a user ID, called the publisher. The GRANT PUBLISH
statement identifies the publisher user ID associated with these outgoing
messages.
Only one user ID can have PUBLISH authority. The user ID with PUBLISH
authority is identified by the special constant CURRENT PUBLISHER. The
following query identifies the current publisher:
SELECT CURRENT PUBLISHER
If there is no publisher, the special constant is NULL.
The current publisher special constant can be used as a default setting for
columns. It is often useful to have a CURRENT PUBLISHER column as part
of the primary key for replicating tables, as this helps prevent primary key
conflicts due to updates at more than one site.
In order to change the publisher, you must first drop the current publisher
using the REVOKE PUBLISH statement, and then create a new publisher
using the GRANT PUBLISH statement.
Example GRANT PUBLISH TO publisher_ID

592
Chapter 25 Command Reference for Adaptive Server Anywhere

GRANT REMOTE statement


Function Use this statement to identify a database immediately below the current
database in a SQL Remote hierarchy, who will receive messages from the
current database. These are called remote users.
Syntax GRANT REMOTE TO userid, …
… TYPE message-system, …
… ADDRESS address-string, …
… [ SEND { EVERY | AT } send-time ]
Parameters Parameter Description
userid The user ID for the user to be granted the permission
message-system One of the message systems supported by SQL Remote. It
must be one of the following values:
♦ FILE
♦ FTP
♦ MAPI
♦ SMTP
♦ VIM
address-string A string containing a valid address for the specified message
system.
send-time A string containing a time specification in the form hh:mm.

Permissions Must have DBA authority.


Side effects Automatic commit.
See also "GRANT CONSOLIDATE statement" on page 590
"REVOKE REMOTE statement" on page 600
"GRANT PUBLISH statement" on page 592
"sp_grant_remote procedure" on page 624
"Granting and revoking REMOTE and CONSOLIDATE permissions" on
page 434,
Description In a SQL Remote installation, each database receiving messages from the
current database must be granted REMOTE permissions.
The single exception is the database immediately above the current database
in a SQL Remote hierarchy, which must be granted CONSOLIDATE
permissions.

593
GRANT REMOTE statement

The remote user is identified by a message system, identifying the method by


which messages are sent to and received from the consolidated user. The
address-name must be a valid address for the message-system, enclosed in
single quotes.
For the FILE message type, the address is a subdirectory of the directory
pointed to by the SQLREMOTE environment variable.
The GRANT REMOTE statement is required for the remote database to
receive messages, but does not by itself subscribe the remote user to any
data. To subscribe to data, a subscription must be created for the user ID to
one of the publications in the current database, using the database extraction
utility or the CREATE SUBSCRIPTION statement.
The optional SEND EVERY and SEND AT clauses specify a frequency at
which messages are sent. The string contains a time that is a length of time
between messages (for SEND EVERY) or a time of day at which messages
are sent (for SEND AT). With SEND AT, messages are sent once per day.
If a user has been granted remote permissions without a SEND EVERY or
SEND AT clause, the Message Agent processes messages, and then stops. In
order to run the Message Agent continuously, you must ensure that every
user with REMOTE permission has either a SEND AT or SEND EVERY
frequency specified.
It is anticipated that at many consolidated databases, the Message Agent will
be run continuously, so that all remote databases would have a SEND clause
specified. A typical setup may involve sending messages to laptop users
daily (SEND AT) and to remote servers every hour or two (SEND EVERY).
You should use as few different times as possible, for efficiency.
Example ♦ The following statement grants remote permissions to user SamS, using
a MAPI e-mail system, sending messages to the address Singer, Samuel
once every two hours:
GRANT REMOTE TO SamS
TYPE mapi
ADDRESS ’Singer, Samuel’
SEND EVERY ’02:00’

594
Chapter 25 Command Reference for Adaptive Server Anywhere

GRANT REMOTE DBA statement


Function Use this statement to provide DBA privileges to a user ID, but only when
connected from the Message Agent.
Syntax 1 GRANT REMOTE DBA
TO userid, …
IDENTIFIED BY password
Permissions Must have DBA authority.
Side effects Automatic commit.
See also "The Message Agent and replication security" on page 473
"REVOKE REMOTE DBA statement" on page 601

Description REMOTE DBA authority enables the Message Agent to have full access to
the database in order to make any changes contained in the messages, while
avoiding security problems associated with distributing DBA user IDs
passwords.
REMOTE DBA has the following properties.
♦ No distinct permissions when not connected from the Message Agent. A
user ID granted REMOTE DBA authority has no extra privileges on any
connection apart from the Message Agent. Even if the user ID and
password for a REMOTE DBA user is widely distributed, there is no
security problem. As long as the user ID has no permissions beyond
CONNECT granted on the database, no one can use this user ID to
access data in the database.
♦ Full DBA permissions when connected from the Message Agent.

595
PASSTHROUGH statement

PASSTHROUGH statement
Function Use this statement to start or stop passthrough mode for SQL Remote
administration. Forms 1 and 2 start passthrough mode, while form 3 stops
passthrough mode.
Syntax 1 PASSTHROUGH [ ONLY ] FOR userid, …
Syntax 2 PASSTHROUGH [ ONLY ] FOR SUBSCRIPTION
… TO [ ( owner ) ].publication-name [ ( constant ) ]
Syntax 3 PASSTHROUGH STOP
Permissions Must have DBA authority.
Side effects None.
See also "sp_passthrough procedure" on page 632
Description In passthrough mode, any SQL statements are executed by the database
server, and are also placed into the transaction log to be sent in messages to
subscribers. If the ONLY keyword is used to start passthrough mode, the
statements are not executed at the server; they are sent to recipients only. The
recipients of the passthrough SQL statements are either a list of user IDs
(form 1) or all subscribers to a given publication. Passthrough mode may be
used to apply changes to a remote database from the consolidated database or
send statements from a remote database to the consolidated database.
Syntax 2 sends statements to remote databases whose subscriptions are
started, and does not send statements to remote databases whose
subscriptions are created and not started.
Example PASSTHROUGH FOR rem_db ;

( SQL statements to be executed at the remote database )

PASSTHROUGH STOP ;

596
Chapter 25 Command Reference for Adaptive Server Anywhere

REMOTE RESET statement


Function Use this statement in custom database-extraction procedures to start all
subscriptions for a remote user in a single transaction.
Syntax REMOTE RESET userid
Permissions Must have DBA authority.
Side effects No automatic commit is done by this statement.
See also "START SUBSCRIPTION statement" on page 604
Description This command starts all subscriptions for a remote user in a single
transaction. It sets the log_sent and confirm_sent values in
SYSREMOTEUSER table to the current position in the transaction log. It
also sets the created and started values in SYSSUBSCRIPTION to the
current position in the transaction log for all subscriptions for this remote
user. The statement does not do a commit. You must do an explicit commit
after this call.
In order to write an extraction process that is safe on a live database, the data
must be extracted at isolation level 3 in the same transaction as the
subscriptions are started.
This statement is an alternative to start subscription. START
SUBSCRIPTION has an implicit commit as a side effect, so that if a remote
user has several subscriptions, it is impossible to start them all in one
transaction using START SUBSCRIPTION.
Example ♦ The following statement resets the subscriptions for remote user SamS:
REMOTE RESET SamS

597
REVOKE CONSOLIDATE statement

REVOKE CONSOLIDATE statement


Function Use this statement to stop a consolidated database from receiving
SQL Remote messages from this database.
Syntax REVOKE CONSOLIDATE FROM userid, …
Permissions Must have DBA authority.
Side effects Automatic commit. Drops all subscriptions for the user.
See also "GRANT CONSOLIDATE statement" on page 590
"sp_revoke_consolidate procedure" on page 660
Description CONSOLIDATE permissions must be granted at a remote database for the
user ID representing the consolidated database. The REVOKE
CONSOLIDATE statement removes the consolidated database user ID from
the list of users receiving messages from the current database.
Example ♦ The following statement revokes consolidated status from the user ID
condb:
REVOKE CONSOLIDATE FROM condb

598
Chapter 25 Command Reference for Adaptive Server Anywhere

REVOKE PUBLISH statement


Function Use this statement to terminate the identification of the named user ID as the
CURRENT publisher.
Syntax REVOKE PUBLISH FROM userid
Permissions Must have DBA authority.
Side effects Automatic commit.
See also "GRANT PUBLISH statement" on page 592
"REVOKE REMOTE statement" on page 600
"CREATE PUBLICATION statement" on page 579
"CREATE SUBSCRIPTION statement" on page 583
"sp_publisher procedure" on page 639
Description Each database in a SQL Remote installation is identified in outgoing
messages by a publisher user ID. The current publisher user ID can be found
using the CURRENT PUBLISHER special constant. The following query
identifies the current publisher:
SELECT CURRENT PUBLISHER
The REVOKE PUBLISH statement ends the identification of the named user
ID as the publisher.
You should not REVOKE PUBLISH from a database while the database has
active SQL Remote publications or subscriptions.
Issuing a REVOKE PUBLISH statement at a database has several
consequences for a SQL Remote installation:
♦ You will not be able to insert data into any tables with a CURRENT
PUBLISHER column as part of the primary key. Any outgoing
messages will not be identified with a publisher user ID, and so will not
be accepted by recipient databases.
If you change the publisher user ID at any consolidated or remote database in
a SQL Remote installation, you must ensure that the new publisher user ID is
granted REMOTE permissions on all databases receiving messages from the
database. This will generally require all subscriptions to be dropped and
recreated.
Example REVOKE PUBLISH FROM publisher_ID

599
REVOKE REMOTE statement

REVOKE REMOTE statement


Function Use this statement to stop a user from being able to receive SQL Remote
messages from this database.
Syntax REVOKE REMOTE FROM userid, …
Permissions Must have DBA authority.
Side effects Automatic commit. Drops all subscriptions for the user.
See also "sp_revoke_remote procedure" on page 661
Description REMOTE permissions are required for a user ID to receive messages in a
SQL Remote replication installation. The REVOKE REMOTE statement
removes a user ID from the list of users receiving messages from the current
database.
Example REVOKE REMOTE FROM SamS

600
Chapter 25 Command Reference for Adaptive Server Anywhere

REVOKE REMOTE DBA statement


Function Use this statement to provide DBA privileges to a user ID, but only when
connected from the Message Agent.
Syntax 1 REVOKE REMOTE DBA
FROM userid, …
Permissions Must have DBA authority.
Side effects Automatic commit.
See also "The Message Agent and replication security" on page 473
"GRANT REMOTE DBA statement" on page 595
Description REMOTE DBA authority enables the Message Agent to have full access to
the database in order to make any changes contained in the messages, while
avoiding security problems associated with distributing DBA user IDs
passwords.
This statement revokes REMOTE DBA authority from a user ID.

601
SET REMOTE OPTION statement

SET REMOTE OPTION statement


Function Use this statement to set a message control parameter for a SQL Remote
message link.
Syntax SET REMOTE link-name OPTION
… [ userid.| PUBLIC.]link-option-name = link-option-value
Parameters link-name:
file | ftp | mapi | smtp | vim
link-option-name:
file-option | ftp-option | mapi-option | smtp-option | vim-option
file-option:
debug | directory
ftp-option:
active_mode | debug | host | password | port | root_directory | user
mapi-option:
debug | force_download | ipm_receive | ipm_send | profile
smtp-option:
debug | local_host | pop3_host | pop3_password | pop3_userid |
smtp_host | top_supported
vim-option:
debug | password | path | receive_all | send_vim_mail | userid
link-option-value:
string
Permissions Must have DBA authority. The publisher can set their own options.
Side effects Automatic commit.
"sp_link_option procedure" on page 626
See also
Description The Message Agent saves message link parameters when the user enters
them in the message link dialog box when the message link is first used. In
this case, it is not necessary to use this statement explicitly. This statement is
most useful when preparing a consolidated database for extracting many
databases.
The option names are case sensitive. The case sensitivity of option values
depends on the option: boolean values are case insensitive, while the case
sensitivity of passwords, directory names, and other strings depend on the
cases sensitivity of the file system (for directory names), or the database (for
user IDs and passwords).

userid If no userid is specified, then the current publisher is assumed.

602
Chapter 25 Command Reference for Adaptive Server Anywhere

Option values The option values are message-link dependent. For more
information, see the following locations:
♦ "The file message system" on page 446.
♦ "The ftp message system" on page 447.
♦ "The MAPI message system" on page 451.
♦ "The SMTP message system" on page 449.
♦ "The VIM message system" on page 452.
Examples The following statement sets the FTP host to ftp.mycompany.com for the ftp
link for user myuser:
SET REMOTE FTP OPTION myuser.host = ’ftp.mycompany.com’

603
START SUBSCRIPTION statement

START SUBSCRIPTION statement


Function Use this statement to start a subscription for a user to a publication.
Syntax START SUBSCRIPTION
… TO publication-name [ ( subscription-value) ]
… FOR subscriber-id, …
Parameters Parameter Description
publication-name The name of the publication to which the user is being
subscribed. This may include the owner of the publication.
subscription-value A string that is compared to the subscription expression of
the publication. The value is required here because each
subscriber may have more than one subscription to a
publication.
subscriber-id The user ID of the subscriber to the publication. This user
must have a subscription to the publication.

Permissions Must have DBA authority.


Side effects Automatic commit.
See also "CREATE SUBSCRIPTION statement" on page 583
"REMOTE RESET statement" on page 597
"SYNCHRONIZE SUBSCRIPTION statement" on page 607
"sp_subscription procedure" on page 662
Description A SQL Remote subscription is said to be started when publication updates
are being sent from the consolidated database to the remote database.
The START SUBSCRIPTION statement is one of a set of statements that
manage subscriptions. The CREATE SUBSCRIPTION statement defines the
data that the subscriber is to receive. The SYNCHRONIZE
SUBSCRIPTION statement ensures that the consolidated and remote
databases are consistent with each other. The START SUBSCRIPTION
statement is required to start messages being sent to the subscriber.
Data at each end of the subscription must be consistent before a subscription
is started. It is recommended that you use the database extraction utility to
manage the creation, synchronization, and starting of subscriptions. If you
use the database extraction utility, you do not need to execute an explicit
START SUBSCRIPTION statement. Also, the Message Agent starts
subscriptions once they are synchronized.
Example The following statement starts the subscription of user SamS to the
pub_contact publication.
START SUBSCRIPTION TO pub_contact

604
Chapter 25 Command Reference for Adaptive Server Anywhere

FOR SamS

605
STOP SUBSCRIPTION statement

STOP SUBSCRIPTION statement


Function Use this statement to stop a subscription for a user to a publication.
Syntax STOP SUBSCRIPTION
… TO publication-name [ ( subscription-value) ]
… FOR subscriber-id, …
Parameters Parameter Description
publication-name The name of the publication to which the user is being
subscribed. This may include the owner of the publication.
subscription-value A string that is compared to the subscription expression of
the publication. The value is required here because each
subscriber may have more than one subscription to a
publication.
subscriber-id The user ID of the subscriber to the publication. This user
must have a subscription to the publication.

Permissions Must have DBA authority.


Side effects Automatic commit.
See also "CREATE SUBSCRIPTION statement" on page 583
"SYNCHRONIZE SUBSCRIPTION statement" on page 607
Description A SQL Remote subscription is said to be started when publication updates
are being sent from the consolidated database to the remote database.
The STOP SUBSCRIPTION statement prevents any further messages being
sent to the subscriber. The START SUBSCRIPTION statement is required to
restart messages being sent to the subscriber. However, you should ensure
that the subscription is properly synchronized before restarting: that no
messages have been missed.
Example The following statement starts the subscription of user SamS to the
pub_contact publication.
STOP SUBSCRIPTION TO pub_contact
FOR SamS

606
Chapter 25 Command Reference for Adaptive Server Anywhere

SYNCHRONIZE SUBSCRIPTION statement


Function Use this statement to synchronize a subscription for a user to a publication.
Syntax SYNCHRONIZE SUBSCRIPTION
… TO publication-name [ ( subscription-value) ]
… FOR remote-user, …
Parameters Parameter Description
publication-name The name of the publication to which the user is being
subscribed. This may include the owner of the publication.
subscription-value A string that is compared to the subscription expression of
the publication. The value is required here because each
subscriber may have more than one subscription to a
publication.
remote-user The user ID of the subscriber to the publication. This user
must have a subscription to the publication.

Permissions Must have DBA authority.


Side effects Automatic commit.
See also "CREATE SUBSCRIPTION statement" on page 583
"START SUBSCRIPTION statement" on page 604
Description A SQL Remote subscription is said to be synchronized when the data in the
remote database is consistent with that in the consolidated database, so that
publication updates sent from the consolidated database to the remote
database will not result in conflicts and errors.
To synchronize a subscription, a copy of the data in the publication at the
consolidated database is sent to the remote database. The SYNCHRONIZE
SUBSCRIPTION statement does this through the message system. It is
recommended that where possible you use the database extraction utility
instead to synchronize subscriptions without using a message system.
Example The following statement synchronizes the subscription of user SamS to the
pub_contact publication.
SYNCHRONIZE SUBSCRIPTION TO pub_contact
FOR SamS

607
UPDATE statement

UPDATE statement
Function Use this statement to modify data in the database.
Syntax 1 UPDATE table-list
… SET column-name = expression, …
… [ FROM table-list ]
… [ WHERE search-condition ]
… [ ORDER BY expression [ ASC | DESC ] , … ]
Syntax 2 UPDATE table-list
… SET column-name = expression, …
… [ VERIFY ( column-name, … ) VALUES ( expression, … ) ]
… [ WHERE search-condition ]
… [ ORDER BY expression [ ASC | DESC ] , … ]
Syntax 3 UPDATE table
…PUBLICATION publication
…{ SUBSCRIBE BY expression |
OLD SUBSCRIBE BY expression
NEW SUBSCRIBE BY expression
}
…WHERE search-condition
expression: value | subquery
Usage Syntax 1 can be used anywhere.
Syntax 2 and Syntax 3 are applicable only to SQL Remote.
Syntax 3 with no OLD and NEW SUBSCRIBE BY expressions must be
used in a BEFORE trigger.
Syntax 3 with OLD and NEW SUBSCRIBE BY expressions can be used
anywhere.
Permissions Must have UPDATE permission for the columns being modified.
Side effects None.
"CREATE TRIGGER statement" on page 584
See also
Description The UPDATE statement is used to modify rows of one or more tables. Each
named column is set to the value of the expression on the right hand side of
the equal sign. There are no restrictions on the expression. Even column-
name can be used in the expression—the old value will be used.
If no WHERE clause is specified, every row will be updated. If a WHERE
clause is specified, then only those rows which satisfy the search condition
will be updated.

608
Chapter 25 Command Reference for Adaptive Server Anywhere

Normally, the order that rows are updated doesn’t matter. However, in
conjunction with the NUMBER(*) function, an ordering can be useful to get
increasing numbers added to the rows in some specified order. Also, if you
wish to do something like add 1 to the primary key values of a table, it is
necessary to do this in descending order by primary key, so that you do not
get duplicate primary keys during the operation.
Views can be updated provided the SELECT statement defining the view
does not contain a GROUP BY clause, an aggregate function, or involve a
UNION operation.
Character strings inserted into tables are always stored in the case they are
entered, regardless of whether the database is case sensitive or not. Thus a
character data type column updated with a string Value is always held in the
database with an upper-case V and the remainder of the letters lower case.
SELECT statements return the string as Value. If the database is not case-
sensitive, however, all comparisons make Value the same as value,
VALUE, and so on. Further, if a single-column primary key already contains
an entry Value, an INSERT of value is rejected, as it would make the
primary key not unique.
Updates based on The optional FROM clause allows tables to be updated based on joins. If the
joins FROM clause is present, the WHERE clause qualifies the rows of the FROM
clause. Data is updated only in the table list immediately following the
UPDATE keyword.
If a FROM clause is used, it is important to qualify the table name that is
being updated the same way in both parts of the statement. If a correlation
name is used in one place, the same correlation name must be used in the
other. Otherwise, an error is generated.
SQL Remote Syntax 2 is intended for use with SQL Remote only, in single-row updates
updates executed by the Message Agent. The VERIFY clause contains a set of values
that are expected to be present in the row being updated. If the values do not
match, any RESOLVE UPDATE triggers are fired before the UPDATE
proceeds. The UPDATE does not fail if the VERIFY clause fails to match.
Syntax 3 is intended for use with SQL Remote only. If no OLD and NEW
expressions are used, it must be used inside a BEFORE trigger so that it has
access to the relevant values. The purpose is to provide a full list of subscribe
by values any time the list changes. It is placed in SQL Remote triggers so
that the database server can compute the current list of SUBSCRIBE BY
values. Both lists are placed in the transaction log.
The Message Agent uses the two lists to make sure that the row moves to any
remote database that did not have the row and now needs it. The Message
Agent also removes the row from any remote database that has the row and
no longer needs it. A remote database that has the row and still needs it is not
be affected by the UPDATE statement.

609
UPDATE statement

Performance tip Syntax 3 of the UPDATE statement allows the old SUBSCRIBE BY list and
the new SUBSCRIBE BY list to be explicitly specified, which can make
SQL Remote triggers more efficient. In the absence of these lists, the
database server computes the old SUBSCRIBE BY list from the publication
definition. Since the new SUBSCRIBE BY list is commonly only slightly
different from the old SUBSCRIBE BY list, the work to compute the old list
may be done twice. By specifying both the old and new lists, this extra work
can be avoided.
The OLD and NEW SUBSCRIBE BY syntax is especially useful when many
tables are being updated in the same trigger with the same subscribe by
expressions. This can dramatically increase performance.
The SUBSCRIBE BY expression is either a value or a subquery.
Using UPDATE to Syntax 3 of the UPDATE statement is used to implement a specific
maintain SQL Remote feature, and is to be used inside a BEFORE trigger.
subscriptions For publications created using a subquery in a subscription expression, you
must write a trigger containing syntax 3 of the UPDATE statement in order
to ensure that the rows are kept in their proper subscriptions.
$ For a full description of this feature, see "Territory realignment in the
Contact example" on page 333.
Syntax 3 of the UPDATE statement makes an entry in the transaction log,
but does not change the database table.
Examples ♦ Transfer employee Philip Chin (employee 129) from the sales
department to the marketing department.
UPDATE employee
SET dept_id = 400
WHERE emp_id = 129 ;

610
C H A P T E R 2 6

Command Reference for Adaptive Server


Enterprise

About this chapter This chapter describes the SQL Remote stored procedures, used for
executing SQL Remote commands.
Contents
Topic Page
sp_add_article procedure 613
sp_add_article_col procedure 615
sp_add_remote_table procedure 616
sp_create_publication procedure 618
sp_drop_publication procedure 619
sp_drop_remote_type procedure 620
sp_drop_sql_remote procedure 621
sp_grant_consolidate procedure 622
sp_grant_remote procedure 624
sp_link_option procedure 626
sp_modify_article procedure 628
sp_modify_remote_table procedure 630
sp_passthrough procedure 632
sp_passthrough_piece procedure 633
sp_passthrough_stop procedure 635
sp_passthrough_subscription procedure 636
sp_passthrough_user procedure 637
sp_populate_sql_anywhere procedure 638
sp_publisher procedure 639
sp_queue_clean procedure 640
sp_queue_confirmed_delete_old procedure 641

611
sp_add_article procedure

sp_queue_confirmed_transaction procedure 642


sp_queue_delete_old procedure 643
sp_queue_drop procedure 644
sp_queue_dump_database procedure 645
sp_queue_dump_transaction procedure 646
sp_queue_get_state procedure 647
sp_queue_log_transfer_reset procedure 648
sp_queue_read procedure 649
sp_queue_reset procedure 650
sp_queue_set_confirm procedure 651
sp_queue_set_progress procedure 652
sp_queue_transaction procedure 653
sp_remote procedure 654
sp_remote_option procedure 655
sp_remote_type procedure 656
sp_remove_article procedure 657
sp_remove_article_col procedure 658
sp_remove_remote_table procedure 659
sp_revoke_consolidate procedure 660
sp_revoke_remote procedure 661
sp_subscription procedure 662
sp_subscription_reset procedure 663

612
Chapter 26 Command Reference for Adaptive Server Enterprise

sp_add_article procedure
Purpose To add an article to a publication.
Syntax sp_add_article publication_name, table_name, where_expr,
subscribe_by_expr, subscribe_by_view

Argument Description
publication_name The name of the publication to which the article is to be
added.
table_name The table containing the article.
where_expr This optional argument must be a column name or
NULL. The publication includes only rows for which the
supplied column value is not NULL.
The default value is NULL, in which case no rows are
excluded from the publication.
subscribe_by_expr The new subscription expression defining which rows are
to be included in the publication for each subscription.
The expression must be the name of a column in
table_name. The default value is NULL.
subscribe_by_view A view defining the columns and rows to be included in
the publication.

$ For more information, see "Tuning extraction


performance" on page 384 and "Tuning extraction
performance for shared rows" on page 391.

See also "sp_add_remote_table procedure" on page 616


"sp_create_publication procedure" on page 618
"sp_remove_article procedure" on page 657
"CREATE PUBLICATION statement" on page 579
Description Running sp_add_article adds an article to a publication. The table must be
marked for replication using sp_add_remote_table before it can be added to
a publication; failure to do so leads to an error.
Calling sp_add_article adds all the columns of the table to a publication. If
you wish to include only some of the columns of the table in a publication
you must first run sp_add_article and then call sp_add_article_col.
As with other data definition changes, in a production environment this
procedure should only be run on a quiet SQL Remote installation.
$ For more information on the requirements for a quiet system, see
"Making schema changes" on page 506.

613
sp_add_article procedure

Example ♦ The following statement adds the SalesRep table to a publication named
SalesRepData:
sp_add_article ’SalesRepData’, ’SalesRep’
go

614
Chapter 26 Command Reference for Adaptive Server Enterprise

sp_add_article_col procedure
Purpose To add a column to an article in a publication.
Syntax sp_add_article_col publication_name, table_name, column_name

Argument Description
publication_name The name of the publication to which the article is to be
added.
table_name The table containing the article.
column_name The column to be added to the article in a publication

See also "sp_add_article procedure" on page 613


"sp_remove_article procedure" on page 657
"ALTER PUBLICATION statement" on page 577
Description Running sp_add_article_col adds a column to an article in a publication.
The table must first be added to the publication using the "sp_add_article
procedure" on page 613.
To add all the columns of a table to a publication you do not need to use
sp_add_article_col; just call sp_add_article.
To add only some of the columns of a table to a publication you first call
sp_add_article, and then call sp_add_article_col for each of the columns
you wish to include in the publication.
As with other data definition changes, in a production environment this
procedure should only be run on a quiet SQL Remote installation.
$ For more information on the requirements for a quiet system, see
"Making schema changes" on page 506.
Example ♦ The following statements add the emp_id and emp_lname columns of
the employee table to a publication named Personnel:
sp_add_article ’Personnel’, employee’
sp_add_article_col ’Personnel’, ’employee’, ’emp_id’
sp_add_article_col ’Personnel’, ’employee’,
’emp_lname’
go

615
sp_add_remote_table procedure

sp_add_remote_table procedure
Purpose To mark a table for SQL Remote replication.
Syntax sp_add_remote_table table_name,
[ resolve_procedure, ]
[ old_row_name, ]
[ remote_row_name ]

Argument Description
table_name The table to be marked for SQL Remote replication.
resolve_procedure The name of a stored procedure that carries out actions
when a conflict occurs.
old_row_name The name of a table holding the values in the table when
a conflict occurs.
remote_row_name The name of a table holding the values at the remote
database when a conflict-causing UPDATE statement
was applied.

Authorization You must be a system administrator to execute this procedure.


See also "sp_modify_remote_table procedure" on page 630
"sp_remove_remote_table procedure" on page 659
"Managing conflicts" on page 394.
Description Each table in a database must be marked for replication by using
sp_add_remote_table before it can be included in any SQL Remote
publications. After executing sp_add_remote_table, you can add the table
to a publication using the "sp_add_article procedure" on page 613 and the
"sp_add_article_col procedure" on page 615.
The sp_add_remote_table procedure calls sp_setreplicate, which flags the
table for replication. This tells Adaptive Server Enterprise to put extended
information into the transaction log. This information includes the entire
before and after images of the row.
The first argument is the name of the table to be marked for replication.
The remaining three arguments are optional. They are object names required
only for custom conflict resolution. If you are implementing custom conflict
resolution, you must supply the names of two tables, and a stored procedure.
The sp_add_remote_table procedure does not check for the existence of the
conflict resolution arguments: you can create them either before or after
marking the table for replication.
The two tables must have the same columns and data types as table
table_name.

616
Chapter 26 Command Reference for Adaptive Server Enterprise

Examples ♦ The following statement marks the Customer table for replication, using
default conflict resolution:
exec sp_add_remote_table Customer
♦ The following statement marks the Customer table for replication, using
a stored procedure named Customer_Conflict to resolve conflicts. The
old and remote rows are stored in tables named old_Customer and
remote_Customer, respectively:
exec sp_add_remote_table Customer,
Customer_Conflict, old_Customer, remote_Customer

617
sp_create_publication procedure

sp_create_publication procedure
Purpose To create a publication.
Syntax sp_create_publication publication_name

Argument Description
publication_name The name of the publication

See also "sp_drop_publication procedure" on page 619


"CREATE PUBLICATION statement" on page 579
Description Running sp_create_publication creates a publication, but one with no
content. Once the publication is created, you must add articles to it using the
"sp_add_remote_table procedure" on page 616 and the "sp_add_article
procedure" on page 613.
Example ♦ The following statement creates a publication named SalesRepData:
sp_create_publication ’SalesRepData’
go

618
Chapter 26 Command Reference for Adaptive Server Enterprise

sp_drop_publication procedure
Purpose To drop a publication from the database.
Syntax sp_drop_publication publication_name

Argument Description
publication_name The name of the publication to be dropped

See also "sp_create_publication procedure" on page 618


"DROP PUBLICATION statement" on page 587
Description Running sp_drop_publication drops a publication from the database. All
articles that make up the publication, and subscriptions to the publication, are
also dropped.
Example ♦ The following statement drops the publication named SalesRep:
sp_drop_publication ’SalesRep’
go

619
sp_drop_remote_type procedure

sp_drop_remote_type procedure
Purpose To drop a message type from the database.
Syntax sp_drop_remote_type type_name

Argument Description
type_name The message type to drop. This must be a string
containing one of the following:
♦ file
♦ ftp
♦ smtp
♦ mapi
♦ vim

See also "sp_remote_type procedure" on page 656


"DROP REMOTE MESSAGE TYPE statement" on page 588
Description Drops the named message type from the database.
Example ♦ The following statement drops the MAPI message type from the
database:
sp_drop_remote_type mapi
go

620
Chapter 26 Command Reference for Adaptive Server Enterprise

sp_drop_sql_remote procedure
Purpose To drop the SQL Remote system objects from a database.
Syntax sp_drop_sql_remote
See also "sp_queue_drop procedure" on page 644
Description Drops the SQL Remote system objects from the database, so that it can no
longer function in a SQL Remote installation.
The sole SQL Remote object not removed is the sp_drop_sql_remote
procedure itself (a procedure cannot drop itself from a database). To
complete removal of SQL Remote requires that sp_drop_sql_remote be
dropped explicitly after it is called.
The sp_drop_sql_remote procedure does not remove stable queue objects
from the database. To remove the stable queue, use the "sp_queue_drop
procedure" on page 644.
Example ♦ The following statements remove SQL Remote system objects from a
database:
sp_drop_sql_remote_type
go
drop procedure sp_drop_sql_remote
go

621
sp_grant_consolidate procedure

sp_grant_consolidate procedure
Purpose To identify a database immediately above the current database in a
SQL Remote hierarchy, who will receive messages from the current
database. This procedure applies only to Adaptive Server Enterprise
databases acting as remote databases.
Syntax sp_grant_consolidate user_name, type_name, address
[, frequency ] [, send_time ]

Argument Description
user_name The user ID who will be able to receive SQL Remote
messages.
type_name The message type to be used. This must be one of the
following:
♦ file
♦ ftp
♦ smtp
♦ mapi
♦ vim
address A string holding the address, according to the specified
message type, to which the replication messages should
be sent for this user.
frequency A string containing one of the following:
♦ SEND EVERY Indicates that messages are sent at a
frequency specified by send_time.
♦ SEND AT Indicates that messages are sent at a time of
day specified by send_time.

send_time A string containing a time specification with the


following meaning:
♦ If frequency is SEND EVERY, specifies a length of
time between messages.
♦ If frequency is SEND AT, specifies a time of day at
which messages will be sent.

If no frequency is specified, the Message Agent sends


messages, and then stops.

See also "sp_grant_remote procedure" on page 624


"sp_revoke_consolidate procedure" on page 660

622
Chapter 26 Command Reference for Adaptive Server Enterprise

"GRANT CONSOLIDATE statement" on page 590


Description If the Adaptive Server Enterprise server is acting as a remote database in a
SQL Remote installation, the single database above the current database
must be granted consolidated permissions using the sp_grant_consolidate
procedure.
The consolidated user is identified by a message system, identifying the
method by which messages are sent to and received from the consolidated
user. The address-name must be a valid address for the message-system,
enclosed in single quotes.
The sp_grant_consolidate procedure is required for the remote database to
receive messages, but does not by itself subscribe the remote user to any
data. To subscribe to data, a subscription must be created for the user ID to
one of the publications in the current database.
The optional frequency argument specifies a frequency at which messages
are sent. The send_time argument contains a time that is a length of time
between messages (for SEND EVERY) or a time of day at which messages
are sent (for SEND AT). With SEND AT, messages are sent once per day.
If no frequency argument is supplied, the Message Agent processes
messages, and then stops. In order to run the Message Agent continuously,
you must ensure that every user with remote or consolidated permission has
a frequency specified.
Example ♦ The following statement grants consolidated permissions to user
hq_user, using a file sharing system, sending messages to the address
hq_dir: No frequency arguments are specified, and the Message Agent
will run in batch mode.
sp_grant_consolidate
@user_name=hq_user,
@address=hq_dir,
@type_name=file
go

623
sp_grant_remote procedure

sp_grant_remote procedure
Purpose To identify a database immediately below the current database in a
SQL Remote hierarchy, who will receive messages from the current
database. These are called remote users.
Syntax sp_grant_remote user_name, type_name, address
[, frequency ] [, send_time ]

Argument Description
user_name The user ID who will be able to receive SQL Remote
messages.
type_name The message type to be used. This must be one of the
following:
♦ file
♦ ftp
♦ smtp
♦ mapi
♦ vim
address A string holding the address, according to the specified
message type, to which the replication messages should
be sent for this user.
frequency A string containing one of the following:
♦ SEND EVERY Indicates that messages are sent at a
frequency specified by send_time.
♦ SEND AT Indicates that messages are sent at a time of
day specified by send_time.

send_time An optional string containing a time specification with


the following meaning:
♦ If frequency is SEND EVERY, specifies a length of
time between messages.
♦ If frequency is SEND AT, specifies a time of day at
which messages will be sent.

If no frequency is specified, the Message Agent sends


messages, and then stops.

See also "sp_revoke_remote procedure" on page 661


"GRANT REMOTE statement" on page 593

624
Chapter 26 Command Reference for Adaptive Server Enterprise

Description In a SQL Remote installation, each database receiving messages from the
current database must be granted REMOTE permissions using the
sp_grant_remote procedure.
The remote user is identified by a message system, identifying the method by
which messages are sent to and received from the consolidated user. The
address-name must be a valid address for the message-system, enclosed in
single quotes.
The sp_grant_remote procedure is required for the remote database to
receive messages, but does not by itself subscribe the remote user to any
data. To subscribe to data, a subscription must be created for the user ID to
one of the publications in the current database.
The optional frequency argument specifies a frequency at which messages
are sent. The send_time argument contains a time that is a length of time
between messages (for SEND EVERY) or a time of day at which messages
are sent (for SEND AT). With SEND AT, messages are sent once per day.
If no frequency argument is supplied, the Message Agent processes
messages, and then stops. In order to run the Message Agent continuously,
you must ensure that every user with REMOTE permission has a frequency
specified.
It is anticipated that at many consolidated databases, the Message Agent will
be run continuously, so that all remote databases would have a frequency
argument specified. A typical setup may involve sending messages to laptop
users daily (SEND AT) and to remote servers every hour or two (SEND
EVERY). You should use as few different times as possible, for efficiency.
Example ♦ The following statement grants remote permissions to user SamS, using
a MAPI e-mail system, sending messages to the address Singer, Samuel
once every two hours:
exec sp_grant_remote ’SamS’,
’mapi’,
’Singer, Samual’,
’SEND EVERY’,
’02:00’
go

625
sp_link_option procedure

sp_link_option procedure
Purpose To set a message control parameter for a SQL Remote message link.
Syntax sp_link_option link-name, userid, option-name, option-value
Parameters link-name:
file | ftp | mapi | smtp | vim
link-option-name:
file-option | ftp-option | mapi-option | smtp-option | vim-option
file-option:
debug | directory
ftp-option:
active_mode | debug | host | password | port | root_directory | user
mapi-option:
debug | force_download | ipm_receive | ipm_send | profile
smtp-option:
debug | local_host | pop3_host | pop3_password | pop3_userid |
smtp_host | top_supported
vim-option:
debug | password | path | receive_all | send_vim_mail | userid
link-option-value:
string
Permissions Must have DBA authority. The publisher can set their own options.
Side effects Automatic commit.
"SET REMOTE OPTION statement" on page 602
See also
Description The Message Agent saves message link parameters when the user enters
them in the message link dialog box when the message link is first used. In
this case, it is not necessary to use this procedure explicitly. This procedure
is most useful when preparing a consolidated database for extracting many
databases.
The option names are case sensitive. The case sensitivity of option values
depends on the option: boolean values are case insensitive, while the case
sensitivity of passwords, directory names, and other strings depend on the
cases sensitivity of the file system (for directory names), or the database (for
user IDs and passwords).

userid If no userid is specified, then the current publisher is assumed.

Option values The option values are message-link dependent. For more
information, see the following locations:

626
Chapter 26 Command Reference for Adaptive Server Enterprise

♦ "The file message system" on page 446.


♦ "The ftp message system" on page 447.
♦ "The MAPI message system" on page 451.
♦ "The SMTP message system" on page 449.
♦ "The VIM message system" on page 452.
Example The following statement sets the FTP host to ftp.mycompany.com for the ftp
link for user myuser:
exec sp_link_option ftp, myuser,
host, ’ftp.mycompany.com’

627
sp_modify_article procedure

sp_modify_article procedure
Purpose To change the description of an article in a procedure.
Syntax sp_modify_article
publication_name,
table_name,
[ where_expr, ]
[ subscribe_by_expr ]
[ subscribe_by_view ]

Argument Description
publication_name The name of the publication for which the article is to be
modified.
table_name The table containing the article.
where_expr This optional argument must be a column name or
NULL. The publication includes only rows for which the
supplied column name is not NULL.
The default value is NULL, in which case no rows are
excluded from the publication..
subscribe_by_expr The new subscription expression defining which rows are
to be included in the publication for each subscription.
The default value is NULL.
subscribe_by_view A view defining the rows and columns to be included in
the publication. The default is NULL.
$ For more information, see "Tuning extraction
performance" on page 384 and "Tuning extraction
performance for shared rows" on page 391.

See also "sp_add_article procedure" on page 613


"sp_remove_article procedure" on page 657
"ALTER PUBLICATION statement" on page 577
Description To change the description of an article in a publication. The WHERE
expression, the subscription expression, and the subscription view can each
be changed.
As with other data definition changes, in a production environment this
procedure should only be run on a quiet SQL Remote installation.
$ For more information on the requirements for a quiet system, see
"Making schema changes" on page 506.

628
Chapter 26 Command Reference for Adaptive Server Enterprise

Examples The following statement changes an article in the SalesRepData publication


that takes information from the Customer table, so that it has no subscription
expression:
sp_modify_article SalesRepData, Customer
go
The following statement changes an article in the SalesRepData publication
that takes information from the Customer table, so that it has a subscription
expression that is the rep_key column:
sp_modify_article SalesRepData, Customer,
NULL, rep_key
go

629
sp_modify_remote_table procedure

sp_modify_remote_table procedure
Purpose To change the resolution objects for a table marked for SQL Remote
replication.
Syntax sp_modify_remote_table table_name,
[ resolve_name, ]
[ old_row_name, ]
[ remote_row_name ]

Argument Description
table_name A table marked for SQL Remote replication.
resolve_procedure The name of the new stored procedure for carrying out
actions when a conflict occurs.
old_row_name The name of the new table for holding the values in the
table when a conflict occurs.
remote_row_name The name of the new table for holding the values at the
remote database when a conflict-causing UPDATE
statement was applied.

See also "sp_add_remote_table procedure" on page 616


"sp_remove_remote_table procedure" on page 659
"Managing conflicts" on page 394.
Description Each table in a database must be marked for replication by using
sp_add_remote_table before it can be included in any SQL Remote
publications.
The sp_modify_remote_table allows you to change the way in which
conflict resolution is carried out for update conflicts occurring on this table.
The arguments are, in addition to the table name, the object names required
for custom conflict resolution. If you are implementing custom conflict
resolution, you must supply the names of two tables, and a stored procedure.
The sp_modify_remote_table procedure does not check for the existence of
the conflict resolution arguments: you can create them either before or after
marking the table for replication.
The two tables must have the same columns and data types as table
table_name.
Example The following statement instructs SQL Remote to use the resolve_Cust
procedure, the old_Cust table, and the remote_Cust table to resolve update
conflicts on the Customer table:

630
Chapter 26 Command Reference for Adaptive Server Enterprise

sp_add_remote_table Customer, resolve_Cust,


old_Cust, remote_Cust
go

631
sp_passthrough procedure

sp_passthrough procedure
Purpose To send a SQL statement in passthrough mode.
Syntax sp_passthrough statement

Argument Description
statement A string containing a statement to be executed in
passthrough mode.

See also "sp_passthrough_piece procedure" on page 633


"sp_passthrough_stop procedure" on page 635
"sp_passthrough_subscription procedure" on page 636
"sp_passthrough_user procedure" on page 637
"PASSTHROUGH statement" on page 596
Description To send passthrough operations. The recipients of the passthrough statement
are determined by previous calls to sp_passthrough_user and
sp_passthrough_subscription.
The string must be less than 255 characters long. For SQL statements longer
than 255 characters, you should execute a sequence of calls to the
sp_passthrough_piece procedures, and execute sp_passthrough for the
final piece of the statement and to cause the replication to occur.

Caution
You should always test your passthrough operations on a test database
with a remote database subscribed. You should never run untested
passthrough scripts against a production database.

Example ♦ The following statement sends a create table statement to the current
recipients of passthrough statements.
exec sp_passthrough
’CREATE TABLE simple (
id integer NOT NULL,
name char(50) )’
go

632
Chapter 26 Command Reference for Adaptive Server Enterprise

sp_passthrough_piece procedure
Purpose To build a long SQL statement for passthrough.
Syntax sp_passthrough_piece string

Argument Description
string A piece of a statement to be executed in passthrough
mode.

See also "sp_passthrough procedure" on page 632


"sp_passthrough_stop procedure" on page 635
"sp_passthrough_subscription procedure" on page 636
"sp_passthrough_user procedure" on page 637
"PASSTHROUGH statement" on page 596
Description The "sp_passthrough procedure" on page 632 is used to send statements
directly to a set of remote users. Statements that are longer than 255
characters have to be built up piece by piece.
To build and send a long SQL statement, call sp_passthrough_piece for all
but the final piece of the statement, and then call sp_passthrough for the
final piece. This completes and replicates the statement.
All pieces of a passthrough statement must be built within a single transation.
Example ♦ The following statements send a long passthrough statement to the
current list of passthrough recipients:
begin transaction
go
exec sp_passthrough_piece ’CREATE TABLE
DBA.employee
(
emp_id integer NOT NULL,
manager_id integer NULL,
emp_fname char(20) NOT NULL,
emp_lname char(20) NOT NULL,’
go
exec sp_passthrough_piece ’
dept_id integer NOT NULL,
street char(40) NOT NULL,
city char(20) NOT NULL,
state char(4) NOT NULL,
zip_code char(9) NOT NULL,
phone char(10) NULL,’
go
exec sp_passthrough_piece ’status char(1) NULL,
ss_number char(11) NOT NULL,

633
sp_passthrough_piece procedure

salary numeric(20,3) NOT NULL,


start_date date NOT NULL,
termination_date date NULL,
birth_date date NULL,’
go
exec sp_passthrough ’
bene_health_ins char(1) NULL,
bene_life_ins char(1) NULL,
bene_day_care char(1) NULL,
sex char(1) NULL,
PRIMARY KEY (emp_id),
)’
go
commit
go

634
Chapter 26 Command Reference for Adaptive Server Enterprise

sp_passthrough_stop procedure
Purpose Resents passthrough mode
Syntax sp_passthrough_stop
See also "sp_passthrough procedure" on page 632
"sp_passthrough_subscription procedure" on page 636
"sp_passthrough_user procedure" on page 637
"PASSTHROUGH statement" on page 596
Description The sp_passthrough_stop procedure resents the list of recipients of
passthrough statements to be empty, and clears any statements that are
currently being built.
Example ♦ The following statement resets the passthrough recipient list to be
empty.
exec sp_passthrough_stop
go

635
sp_passthrough_subscription procedure

sp_passthrough_subscription procedure
Purpose Adds subscribers to a given publication to the recipient list for passthrough
statements.
Syntax sp_passthrough_subscription publication_name, subscribe_by

Argument Description
publication_name The name of the publication
subscribe_by The subscription value for recipients to receive
passthrough statements.

See also "sp_passthrough procedure" on page 632


"sp_passthrough_piece procedure" on page 633
"sp_passthrough_stop procedure" on page 635
"sp_passthrough_user procedure" on page 637
"PASSTHROUGH statement" on page 596
Description This is one of two ways that you can add to the list of recipients for
passthrough statements, the other being to use the "sp_passthrough_user
procedure" on page 637.
The users that are added to the recipient list by a call to the
sp_passthrough_subscription procedure are all those users subscribing to
the publication publication_name with a subscription value of subscribe_by.
The default setting for subscribe_by is NULL. In this case, all subscribers to
the publication receive the passthrough statements.
Example ♦ The following statement adds to the list of passthrough recipients the
subscriber or subscribers to the SalesRepData publication who use
subscription values of ’rep1’.
Sp_passthrough_subscription SalesRepData, rep1

636
Chapter 26 Command Reference for Adaptive Server Enterprise

sp_passthrough_user procedure
Purpose Adds a named user to the list of recipients for passthrough statements.
Syntax sp_passthrough_user user_name

Argument Description
user_name The user to be added to the list of recipients.

See also "sp_passthrough procedure" on page 632


"sp_passthrough_piece procedure" on page 633
"sp_passthrough_stop procedure" on page 635
"sp_passthrough_subscription procedure" on page 636
"PASSTHROUGH statement" on page 596
Description This is one of two ways that you can add to the list of recipients for
passthrough statements, the other being to use the
"sp_passthrough_subscription procedure" on page 636.
The sp_passthrough_user procedure adds the named user to the list of
recipients for passthrough statements. The list remains in force until reset
using the "sp_passthrough_stop procedure" on page 635.
Example ♦ The following statement adds the user field_user to the list of recipients
for passthrough statements:
sp_passthrough_user ’field_user’
go

637
sp_populate_sql_anywhere procedure

sp_populate_sql_anywhere procedure
Purpose To create a copy of the Adaptive Server Anywhere system tables in the
TEMPDB. This procedure is used by the extraction utility ssxtract.
Syntax sp_populate_sql_anywhere
Description To create a set of Adaptive Server Anywhere system tables for a remote
Adaptive Server Anywhere database, in TEMPDB. The information is used
by the extraction utility to construct an Adaptive Server Anywhere database
schema from the set of publications in the Adaptive Server Enterprise
consolidated database.
This procedure is used by the ssxtract extraction utility. It should not be
called directly.

638
Chapter 26 Command Reference for Adaptive Server Enterprise

sp_publisher procedure
Purpose To set the publisher of the current database, or to remove the publisher.
Syntax sp_publisher [ user_name ]

Argument Description
user_name The user ID to be identifies as the publisher for the
database.

See also "Managing SQL Remote permissions" on page 431.


"GRANT PUBLISH statement" on page 592
Description Each database in a SQL Remote installation is identified in outgoing
messages by a user ID, called the publisher. The sp_publisher procedure
sets the publisher user ID associated with these outgoing messages.
Each database can have at most one publisher; if a publisher already exists,
sp_publisher changes the name of the publisher.
If no user_name argument is provided, the current publisher is removed, so
that the database has no publisher. Only the permission to be the publisher is
removed; the user ID is not removed from the database.
Examples ♦ The following statement identifies the user ID joe as the publisher of the
current database:
sp_publisher joe
go
♦ The following statement sets the current database to have no publisher:
sp_publisher
go

639
sp_queue_clean procedure

sp_queue_clean procedure
Purpose This procedure is used by the SQL Remote Message Agent, and should not
be called directly.
Syntax sp_queue_clean
Description This procedure is used by the SQL Remote Message Agent, and should not
be called directly. It removes from the stable queue any transactions that
completed after the start of the oldest incomplete transaction the last time the
log was scanned.

640
Chapter 26 Command Reference for Adaptive Server Enterprise

sp_queue_confirmed_delete_old procedure
Purpose This procedure is used by the SQL Remote Message Agent, and should not
be called directly.
Syntax sp_queue_confirmed_delete_old
Description This procedure is used by the SQL Remote Message Agent, and should not
be called directly. It removes from the stable queue any transactions whose
offsets are shown in sr_confirmed_transaction.

641
sp_queue_confirmed_transaction procedure

sp_queue_confirmed_transaction procedure
Purpose This procedure is used by the SQL Remote Message Agent, and should not
be called directly.
Syntax sp_queue_confirmed_transaction offset
Description This procedure is used by the SQL Remote Message Agent, and should not
be called directly. It adds the supplied offset to sr_confirmed_transaction.
SQL Remote removes from the stable queue any transactions whose offsets
match this offset.

642
Chapter 26 Command Reference for Adaptive Server Enterprise

sp_queue_delete_old procedure
Purpose This procedure is used by the SQL Remote Message Agent, and should not
be called directly.
Syntax sp_queue_delete_old
Description This procedure is used by the SQL Remote Message Agent, and should not
be called directly. It deletes from the stable queue any transactions that have
been confirmed by all remote databases.

643
sp_queue_drop procedure

sp_queue_drop procedure
Purpose To drop the stable queue objects from a database..
Syntax sp_queue_drop
See also "sp_drop_sql_remote procedure" on page 621
Description Drops the stable queue system objects from the database, so that the database
no longer supports a SQL Remote stable queue.
The sole stable queue object not removed is the sp_queue_drop procedure
itself (a procedure cannot drop itself from a database). To complete removal
of the stable queue requires that sp_queue_drop be dropped explicitly after
it is called.
The sp_queue_drop procedure does not remove SQL Remote system
objects from the database. To remove the SQL Remote system objects, use
the "sp_drop_sql_remote procedure" on page 621.
Examples ♦ The following statements remove the stable queue objects from the
database:
sp_queue_drop
go
drop procedure sp_queue_drop
go

644
Chapter 26 Command Reference for Adaptive Server Enterprise

sp_queue_dump_database procedure
Purpose To facilitate recovery from media failure when the stable queue is in a
separate database from the SQL Remote objects.
Syntax sp_queue_dump_database
See also "sp_queue_dump_transaction procedure" on page 646
"Stable queue recovery issues" on page 504
Description Keeping the stable queue in a separate database complicates backup and
recovery, as consistent versions of the two databases have to be recovered.
Normal recovery automatically restores the two databases to a consistent
state, but recovery from media failure takes some care. When restoring
database dumps, it is important to recover the stable queue to a consistent
point. The sp_queue_dump_database procedure is provided to help with
recovery from media failure. It is called whenever a dump database is
scanned.
As provided, the procedure does not carry out any operations. You can
modify this stored procedure to issue a dump database command in the
stable store database.

645
sp_queue_dump_transaction procedure

sp_queue_dump_transaction procedure
Purpose To facilitate recovery from media failure, when the stable queue is in a
separate database from the SQL Remote objects.
Syntax sp_queue_dump_transaction
See also "sp_queue_dump_database procedure" on page 645
"Stable queue recovery issues" on page 504
Description Keeping the stable queue in a separate database complicates backup and
recovery, as consistent versions of the two databases have to be recovered.
Normal recovery automatically restores the two databases to a consistent
state, but recovery from media failure takes some care. When restoring
database dumps, it is important to recover the stable queue to a consistent
point. The sp_queue_dump_transaction procedure is provided to help with
recovery from media failure. It is called whenever a dump transaction is
scanned.
As provided, the procedure does not carry out any operations. You can
modify this stored procedure to issue a dump transaction command in the
stable store database.

646
Chapter 26 Command Reference for Adaptive Server Enterprise

sp_queue_get_state procedure
Purpose This procedure is used by the SQL Remote Message Agent, and should not
be called directly.
Syntax sp_queue_get_state
Description This procedure is used by the SQL Remote Message Agent, and should not
be called directly. It returns a description of the current state of the stable
queue.

647
sp_queue_log_transfer_reset procedure

sp_queue_log_transfer_reset procedure
Purpose This procedure is used by the SQL Remote Message Agent, and should not
be called directly.
Syntax sp_queue_log_transfer_reset
Description This procedure is used by the SQL Remote Message Agent, and should not
be called directly. It resets the page and row IDs to zero in the
sr_queue_state table.

648
Chapter 26 Command Reference for Adaptive Server Enterprise

sp_queue_read procedure
Purpose This procedure is used by the SQL Remote Message Agent, and should not
be called directly.
Syntax sp_queue_read start_offset, stop_offset
Description This procedure reads transactions from the stable queue. It is exclusively for
use by the Message Agent.

649
sp_queue_reset procedure

sp_queue_reset procedure
Purpose To reset the server to a point where the stable queue is empty.
Syntax sp_queue_reset
Description This procedure is used by the SQL Remote Message Agent, and should not
be called directly in a production environment. It deletes all rows from the
stable queue sr_transaction table, and resets the sr_queue_state table,
ready for a new SQL Remote setup.
In a development phase, this procedure can be useful to reset the server.

650
Chapter 26 Command Reference for Adaptive Server Enterprise

sp_queue_set_confirm procedure
Purpose This procedure is used by the SQL Remote Message Agent, and should not
be called directly.
Syntax sp_queue_set_confirm confirm_offset
Description This procedure is used by the SQL Remote Message Agent, and should not
be called directly. It sets the minimum confirmation offset from all remote
users in the sr_queue_state table.

651
sp_queue_set_progress procedure

sp_queue_set_progress procedure
Purpose This procedure is used by the SQL Remote Message Agent, and should not
be called directly.
Syntax sp_queue_set_progress page_id, row_id, commit_offset, backup_offset,
marker
Description This procedure is used by the SQL Remote Message Agent, and should not
be called directly. It sets the transaction log scanning progress value in the
sr_queue_state table.

652
Chapter 26 Command Reference for Adaptive Server Enterprise

sp_queue_transaction procedure
Purpose This procedure is used by the SQL Remote Message Agent, and should not
be called directly.
Syntax sp_queue_transaction offset, user_id
Description This procedure is used by the SQL Remote Message Agent, and should not
be called directly. It adds a new transaction to the stable queue.

653
sp_remote procedure

sp_remote procedure
Purpose This procedure is used by the SQL Remote Message Agent, and should not
be called directly, with a single exception described below. It manages rows
in the sr_remoteuser table.
Syntax sp_remote operation, user_name [ , offset ] [ , confirm ]

Argument Description
operation The name of an action. The only value that should be
used by a user is reset; all others are for use by the
Message Agent.
user_name The name of the remote user being reset
offset Not used
confirm Not used

Description This procedure is used by the SQL Remote Message Agent, and should not
be called directly with the single exception of the reset call. It maintains the
message tracking information in the sr_remoteuser table.
The following special case can be used directly, when creating a custom
database extraction process:
sp_remote reset, remote_user
where remote_user is the remote user name.
This command starts all subscriptions for a remote user in a single
transaction. It sets the log_sent and confirm_sent values in sr_remoteuser
table to the current position in the transaction log. It also sets the created and
started values in sr_subscription to the current position in the transaction
log for all subscriptions for this remote user. The procedure does not do a
commit. You must do an explicit commit after this call.
In order to write an extraction process that is safe on a live database, the data
must be extracted at isolation level 3 in the same transaction as the
subscriptions are started.

654
Chapter 26 Command Reference for Adaptive Server Enterprise

sp_remote_option procedure
Purpose To set a SQL Remote option.
Syntax sp_remote_option option_name, option_value

Argument Description
option_name The name of one of the SQL Remote options
option_value The value to which the option is set.

See also "SQL Remote options" on page 542.


Description The SQL Remote options provide control over replication behavior. The
following options are available in Adaptive Server Enterprise:

OPTION VALUES DEFAULT


Blob_threshold Integer, in K 256
Compression -1 to 9 6
Delete_old_logs ON, OFF OFF
Qualify_owners ON, OFF OFF
Quote_all_identifiers ON, OFF OFF
Replication_error procedure-name NULL
SR_Date_Format time-string hh:nn:ss.Ssssss
SR_Time_Format date-string yyyy/mm/dd
SR_Timestamp_Format timestamp-string yyyy/mm/dd
hh:nn:ss.Ssssss
Subscribe_by_remote ON,OFF ON
Verify_threshold integer 256
Verify_all_columns ON,OFF OFF

$ For a complete description of these options, see "SQL Remote options"


on page 542.
Example ♦ The following statement sets the Verify_all_columns option to OFF, so
that old values of update statements applied by the Message Agent are
not checked automatically for all columns.
sp_remote_option Verify_all_columns, OFF
go

655
sp_remote_type procedure

sp_remote_type procedure
Purpose To create or modify a SQL Remote message type.
Syntax sp_remote_type type_name publisher_address

Argument Description
type_name The message type to create or alter. This must be one of
the following:
♦ file
♦ ftp
♦ smtp
♦ mapi
♦ vim
publisher_address The address of the publisher under the specified message
type.

See also "sp_drop_remote_type procedure" on page 620


"ALTER REMOTE MESSAGE TYPE statement" on page 578
Description The Message Agent sends outgoing messages from a database using one of
the supported message links. Return messages for users employing the
specified link are sent to the specified address as long as the remote database
is created by the Extraction Utility. The Message Agent starts links only if it
has remote users for those links.
The address is the publisher’s address under the specified message system. If
it is an e-mail system, the address string must be a valid e-mail address. If it
is a file-sharing system, the address string is a subdirectory of the directory
set in the SQLREMOTE environment variable or registry entry, or of the
current directory if that is not set.
Example The following example creates a FILE message type for a database, and
gives the publisher’s address as a subdirectory of the SQLREMOTE location
named publisher:
sp_remote_type file, publisher
go

656
Chapter 26 Command Reference for Adaptive Server Enterprise

sp_remove_article procedure
Purpose To remove an article from a publication
Syntax sp_remove_article publication_name, table_name

Argument Description
publication_name The name of the publication from which the article is to
be deleted.
table_name The table containing the article.

See also "sp_add_article procedure" on page 613


"ALTER PUBLICATION statement" on page 577
Description Running sp_add_article removes an article from a publication. Any article
including parts of the named table is removed from the publication.
Example ♦ The following statement removes any articles that use part of the
SalesRep table from a publication named SalesRepData:
sp_remove_article SalesRepData, SalesRep
go

657
sp_remove_article_col procedure

sp_remove_article_col procedure
Purpose To remove a column from an article in a publication.
Syntax sp_remove_article_col publication_name, article_name, column_name

Argument Description
publication_name The name of the publication to which the article belongs.
article_name The article from which the column is to be removed.
column_name The column to be removed from the article.

See also "sp_add_article_col procedure" on page 615


"sp_remove_article procedure" on page 657
"ALTER PUBLICATION statement" on page 577
Description You can remove a column from a publication using sp_remove_article_col.
To remove a column using sp_remove_article_col, the column must have
been explicitly added to a publication using the "sp_add_article_col
procedure" on page 615. Although the "sp_add_article procedure" on
page 613, without use of sp_add_article_col, adds all the columns of a table
to a publication, you cannot remove a single column from such a publication
using sp_remove_article_col.
Example ♦ The following statement removes the column emp_lname of the
employee table from a publication named Personnel:
sp_remove_article_col ’Personnel’, ’employee’,
’emp_lname’
go

658
Chapter 26 Command Reference for Adaptive Server Enterprise

sp_remove_remote_table procedure
Purpose To mark a table as unavailable for SQL Remote replication.
Syntax sp_remove_remote_table table_name

Argument Description
table_name The table to be marked as not available for SQL Remote
replication.

See also "sp_add_remote_table procedure" on page 616


"sp_modify_remote_table procedure" on page 630
Description Marks a table as unavailable for replication. Once this procedure has been
called, the data in the table cannot be shared with other databases using
SQL Remote.
Example ♦ The following statement marks the employee table as unavailable for
replication:
sp_remove_remote_table employee
go

659
sp_revoke_consolidate procedure

sp_revoke_consolidate procedure
Purpose To stop a user from being able to receive SQL Remote messages from this
database.
sp_revoke_consolidate user_name
Syntax
Argument Description
user_name The user ID who will no longer be able to act as a
consolidated database.

See also "sp_grant_consolidate procedure" on page 622

Description The sp_revoke_consolidate procedure removes the consolidated database


user ID from the list of users receiving messages from the current database.
Example ♦ The following statement revokes consolidated permissions from user
hq_user:
sp_revoke_consolidate hq_user
go

660
Chapter 26 Command Reference for Adaptive Server Enterprise

sp_revoke_remote procedure
Purpose To stop a user from being able to receive SQL Remote messages from this
database.
sp_revoke_remote user_name
Syntax
Argument Description
user_name The user ID who will no longer be able to receive
SQL Remote messages.

See also "sp_grant_remote procedure" on page 624


Description The sp_revoke_remote procedure removes a user ID from the list of users
receiving messages from the current database.
Example ♦ The following statement revokes remote permissions from user Field
User:
sp_revoke_remote ’Field user’
go

661
sp_subscription procedure

sp_subscription procedure
Purpose To manage subscriptions.
Syntax sp_subscription operation,
publication_name,
user_name,
[ subscribe_by ]

Argument Description
operation The operation to be performed. This must be one of the
following:
♦ create To create a subscription to a given publication for
a user.
♦ drop To drop a subscription to a given publication for a
user.
♦ start To start a subscription to the named publication.
♦ stop To stop a subscription to the named publication.
♦ synchronize To synchronize a subscription to the named
publication.

publication_name The name of the publication to which the subscription


refers.
user_name The user ID who is being subscribed to the publication.
subscribe_by The subscription value.

See also "Creating subscriptions" on page 411.


Description The sp_subscription procedure is used to manage subscriptions. The first
argument to the procedure (operation) specified whether the procedure is
being created, dropped, started, stopped, or synchronized.
In general, starting and synchronizing subscriptions is done using the
extraction utility. Sybase Central does not display subscriptions as started
until the Message Agent first runs against the database.
Example The following statement creates a subscription for user SalesRep1 to the
SalesRepData publication, which has no subscription expression.
sp_subscription create,
SalesRepData,
SalesRep1
go

662
Chapter 26 Command Reference for Adaptive Server Enterprise

sp_subscription_reset procedure
Purpose To reset all SQL Remote information for all remote users.
Syntax sp_subscription_reset

Description This procedure resets all the entries in the sr_remote_user and
sr_subscrioption tables to zero or NULL.

663
sp_subscription_reset procedure

664
P A R T F O U R

Appendix

The appendix provides additional information that is not necessarily required


for everyday use of the application.

665
666
A P P E N D I X A

Enterprise and Anywhere: Differences

About this This appendix summarizes the differences between SQL Remote for
Appendix Adaptive Server Enterprise and for Adaptive Server Anywhere.
This appendix describes the main differences between these versions of the
technology.
Contents
Topic Page
Types of difference 668
Differences in functionality 669
Differences in approach 670
Limitations for Enterprise to Enterprise replication 672

667
Types of difference

Types of difference
The differences between the versions of the software are of the following
kinds:
♦ Functionality Tasks that can be carried out by one of the two versions,
but not by the other.
♦ Approach Although a similar result can be obtained, a different
approach is required in each version. This includes tasks that are carried
out in ways that are superficially different, but which have the same
result.
♦ Server differences Tasks associated with SQL Remote, such as
backup management, are different for the two servers. These differences
are not described here.
This appendix addresses only replication using Adaptive Server Anywhere as
remote databases. There are additional limitations if using Adaptive Server
Enterprise as remote servers.

668
Appendix A Enterprise and Anywhere: Differences

Differences in functionality
The major differences in functionality between SQL Remote for Adaptive
Server Enterprise (SRE) and SQL Remote for Adaptive Server Anywhere
(SRA) are as follows:
♦ Schema changes For SRE, schema changes must be made on a quiet
system. A quiet system means the following:
♦ No transactions being replicated There can be no transactions
being replicated that modify the tables that are to be altered. All
transactions that modified tables being altered must be scanned
from the transaction log into the stable queue before the schema is
altered. This is performed by running the Message Agent normally,
or using the -i -b switches. After the Message Agent completes,
you can make the schema change.
♦ Message Agent shut down The Message Agent must be shut
down when the schema change is being made.
♦ SQL Remote Open Server If you are using the SQL Remote
Open Server, it must be shut down when the schema change is
being made.
♦ Trigger action replication In SRE, trigger actions are replicated. In
SRA you have the choice of replicating trigger actions, but by default
they are not replicated. The replication of trigger actions requires SRE
users to ensure that triggers are not fired at remote databases.
♦ Platform availability SRA is available on a wider variety of platforms
that SRE, reflecting the platform availability of the two servers.
♦ Publication definitions Publications in SRA can be more selective
than those in SRE. For example, in SRA you can use a WHERE clause
with any value. In SRE, you can only use IS NULL and IS NOT NULL
conditions in the WHERE clause.

669
Differences in approach

Differences in approach
There are some features of SQL Remote that must be approached in a
different manner in SRE and SRA.
♦ Partitioning tables that do not contain the subscription expression
In SRA, publications can contain subqueries, and these allow tables that
do not contain a partition expression to nevertheless be distributed
properly among subscribers. In SRE, an additional column must be
added to such tables, containing a list of subscribers, and triggers must
be written to maintain the column. This column can have a maximum
size of 255.
$ For descriptions, see "Partitioning tables that do not contain the
subscription expression" on page 330, and "Partitioning tables that do
not contain the subscription column" on page 378.
♦ Conflict resolution In SRA, conflict resolution is carried out using a
special trigger syntax. In SRE, stored procedures must be written to
carry out this task.
$ For descriptions, see "Managing conflicts" on page 347, and
"Managing conflicts" on page 394.
♦ Storing messages before sending In SRE, a separate table named
the stable queue is used to hold changes before replication. In SRA,
there is no stable queue; instead, the messages are retrieved from current
and old transaction log files.
♦ Commands Whereas SQL Remote tasks such as creating publications
are carried out using SQL statements in SRA, they are carried out using
system stored procedures in SRE.
The Sybase Central administration tool hides many of these stylistic
differences by providing a common look and feel to the administration
of each version of SQL Remote.

Adaptive Server Enterprise procedures and Adaptive Server


Anywhere statements
In SQL Remote for Adaptive Server Anywhere, SQL statements are used to
carry out the tasks that these stored procedures carry out in Adaptive Server
Enterprise. The following table lists the SQL Remote procedures, and how
they correspond to SQL statements in Adaptive Server Anywhere:

670
Appendix A Enterprise and Anywhere: Differences

Adaptive Server Enterprise Corresponding Adaptive Server


procedure Anywhere statement
sp_remote_type CREATE REMOTE MESSAGE TYPE
sp_remote_type ALTER REMOTE MESSAGE TYPE
sp_drop_remote_type DROP REMOTE MESSAGE TYPE
sp_grant_remote GRANT REMOTE
sp_revoke_remote REVOKE REMOTE
sp_publisher GRANT PUBLISH
sp_publisher REVOKE PUBLISH
sp_create_publication CREATE PUBLICATION
sp_add_article
sp_add_article_col
sp_add_article ALTER PUBLICATION
sp_remove_article
sp_add_article_col
sp_remove_article_col
sp_drop_publication DROP PUBLICATION
sp_subscription ’create’ CREATE SUBSCRIPTION
sp_subscription ’drop’ DROP SUBSCRIPTION
sp_subscription ’start’ START SUBSCRIPTION
sp_subscription ’stop’ STOP SUBSCRIPTION
sp_subscription ’synchronize’ SYNCHRONIZE SUBSCRIPTION
sp_passthrough_user PASSTHROUGH FOR USERID
sp_passthrough_subscription PASSTHROUGH FOR
SUBSCRIPTION
sp_passthrough_stop PASSTHROUGH STOP

671
Limitations for Enterprise to Enterprise replication

Limitations for Enterprise to Enterprise


replication
If you wish to use SQL Remote for replication between Adaptive Server
Enterprise databases, rather than with Adaptive Server Anywhere remote
databases, you should be aware of the following limitations:
♦ Database extraction The extraction utility creates RELOAD.SQL
scripts and data files for building Adaptive Server Anywhere remote
databases. Setting up remote ASE databases requires an extraction
process created by the customer.
$ For more information about how to create an extraction process,
see "sp_remote procedure" on page 654.
♦ Referential integrity errors Referential integrity is always checked
immediately in Adaptive Server Enterprise, while Adaptive Server
Anywhere provides the WAIT_FOR_COMMIT option to control when
integrity is checked. This presents difficulties when rows move between
remote databases, as in territory realignment.
For example, suppose an Order table has a foreign key to a Customer
table which has a foreign key to a SalesRep table. The Customer table is
subscribed by sales rep. The Order table is also subscribed by sales rep
(it has a redundant column maintained by a trigger).
When a row in Customer is updated to point to a new sales rep, a
trigger fires to update the sales rep column in Order. The update on
Customer is replicated as a delete to the old rep and an insert to the new
rep. Similarly, the triggered update on Order is replicated as a delete to
the old rep and an insert to the new rep.
The problem occurs because SQL Remote replicates the operations in
the order they occur, which means the Customer row is deleted before
the Order rows. This causes a referential integrity error.
♦ Schema upgrades Schema upgrades are difficult to manage when
both consolidated and remote databases are Adaptive Server Enterprise
databases. Passthrough to remote Adaptive Server Enterprise databases
is difficult to carry out.
The problem is due to the need for a quiet system for schema upgrades
(see "Differences in functionality" on page 669). Passthrough puts
schema upgrade statements into the normal message stream. The
operations that precede the schema upgrade (in the same message or a
previous message) cannot possibly have been scanned from the
transaction log into the stable queue before the schema change takes
place.

672
Appendix A Enterprise and Anywhere: Differences

♦ Synchronize subscription This is not implemented for Adaptive


Server Enterprise remote databases.

673
Limitations for Enterprise to Enterprise replication

674
A P P E N D I X B

Supported Platforms and Message Links

About this This appendix summarizes the platforms and message links that
Appendix SQL Remote supports.
Contents
Topic Page
Supported message systems 676
Supported operating systems 677

675
Supported message systems

Supported message systems


SQL Remote exchanges data among databases using an underlying message
system. SQL Remote supports the following message systems:
♦ File sharing A simple system requiring no extra software.
♦ FTP Internet file transfer protocol.
♦ SMTP/POP Internet e-mail protocol.
♦ MAPI Microsoft Messaging Application Programming Interface, used
in Microsoft products and in cc:Mail release 8 and later.
♦ VIM Vendor Independent Messaging, used in Lotus Notes and in some
versions of Lotus cc:Mail.
Not all systems are supported on all operating systems. For all systems other
than the file sharing system, you must have purchased and installed the
appropriate message system software for SQL Remote to function over this
system. SQL Remote does not include the underlying message system
software.

676
Appendix B Supported Platforms and Message Links

Supported operating systems


SQL Remote for SQL Remote for Adaptive Server Enterprise is available for the following
Adaptive Server operating systems and message links:
Enterprise
♦ Windows NT All message protocols.
♦ Sun Microsystems Solaris/Sparc File sharing, FTP, and SMTP/POP
only.
♦ Hewlett-Packard HP-UX File sharing, FTP, and SMTP/POP only.

SQL Remote Open Server on IRIX


A bug in IRIX that was fixed in the IRIX 10.0.3 release EBF 7658 is
required for the SQL Remote Open Server. ssqueue systems
involving SGI/IRIX should make sure this patch is installed.

♦ IBM AIX File sharing only.


SQL Remote for SQL Remote for Adaptive Server Anywhere is available for the following
Adaptive Server operating systems:
Anywhere
♦ Windows 95/98 All message links.
♦ Windows NT All message links.
♦ Windows CE FILE and SMTP/POP links. For the file link, dbremote
looks in \My Documents\Synchronized Files. On the desktop machine,
the SQLREMOTE environment variable or directory message link
parameter for the FILE link should be set to the following:
%SystemRoot%\Profiles\userid\Personal\ce-machine-name\ Synchronized Files

where userid and ce-machine-name are set to the appropriate values.


With this setup, ActiveSync automatically synchronizes the message
files between the desktop and CE system.
Check Mobile Devices➤Tools➤ActiveSync Options to ensure that file
synchronization is activated.
$ For information on setting message link parameters, see "The file
message system" on page 446.
♦ Sun Microsystems Solaris/Sparc File sharing, FTP, and SMTP/POP
only.
♦ Hewlett Packard HP-UX File sharing, FTP, and SMTP/POP only.
♦ IBM AIX File sharing, FTP, and SMTP/POP only.
♦ Novell NetWare File sharing only.

677
Supported operating systems

♦ Linux File sharing, FTP, and SMTP/POP only.


For details of the supported UNIX operating system versions, see the
SQL Anywhere Studio Read Me First for UNIX.

678
Index

Adaptive Server Enterprise


as MobiLink consolidated databases, 38
conversion of data types in MobiLink
# synchronization, 168
#hook_dict table data types, 84
unique primary keys, 359 decimal columns, 84
numeric columns, 84
SQL Remote setup, 235
tutorial with SQL Remote, 269
@ adding
@EmployeeID variable articles, 324
definition, 97 synchronization scripts to consolidated databases,
setting, 97 68
using to partition rows, 101 adding columns
using with primary-key pools, 106 remote MobiLink databases, 115
using with timestamps, 98 adding synchronization scripts
@LastDownload timestamp variable, 96, 99 using stored procedures, 68
definition, 97 adding tables
using, 98 remote MobiLink databases, 115
using for partitioning rows, 101 address
setting for publisher, 442
addresses
file sharing, 447
A ftp, 447
action codes publishers, 578
defined, 81 SMTP, 449
values, 81 SMTP/POP, 451
activating administering
transport-layer security with MobileTrust server- a SQL Remote installation, 429, 430
authentification certificates, 55 administering SQL Remote, 227, 471
ActiveSync administration
Windows CE, 677 overview, 430
Adaptive Server Anywhere ALTER PUBLICATION statement
as MobiLink clients, 31 SQL syntax, 577
as MobiLink clients with transport-layer security, ALTER REMOTE MESSAGE TYPE statement
54 SQL syntax, 578
creating an Enterprise-compatible database, 298 ALTER SYNCHRONIZATION DEFINITION
MobiLink synchronization clients, 131 statement
SQL syntax, 192

679
B–B

ALTER SYNCHRONIZATION SITE statement batches


SQL syntax, 194 passthrough mode, 491
ALTER SYNCHRONIZATION TEMPLATE begin_connection connection script
statement example, 97
SQL syntax, 195 MobiLink syntax, 173
altering begin_connection event
message types, 442, 443 occurrence, 62
publications, 324, 577 begin_connection script
remote message types, 578 example, 91
applications begin_download connection script
differentiating MobiLink scripts, 67 example, 98
article SQL Remote table MobiLink syntax, 173
about, 558 begin_download event
article table occurrence, 76
about, 548 begin_download table script
articlecol SQL Remote table MobiLink syntax, 173
about, 559 begin_download_deletes event
articlecol table occurrence, 76
about, 549 begin_download_deletes table script
articlecols SQL Remote view MobiLink syntax, 174
about, 566 begin_download_rows event
articlecols view occurrence, 76
about, 554 begin_download_rows table script
articles MobiLink syntax, 174
about, 328, 377 begin_synchronization connection script
adding, 324 example, 97
column-wise partitioning, 372 MobiLink syntax, 175
creating, 317 begin_synchronization event
in MobiLink synchronization definitions, 134 occurrence, 62
notes on, 375 begin_synchronization table script
properties, 317 MobiLink syntax, 175
row-wise partitioning, 373 begin_upload connection script
system table for, 549, 559 MobiLink syntax, 176
valid, 328, 377 begin_upload event
whole table, 371 occurrence, 78
articles SQL Remote view begin_upload table script
about, 566 MobiLink syntax, 176
articles view begin_upload_deletes table script
about, 554 MobiLink syntax, 176
begin_upload_rows event
occurrence, 78
begin_upload_rows table script
B MobiLink syntax, 177
b option behavior changes
Message Agent, 455 version 6.0.3, 25, 219
backups version 7.0, 24, 217
for remote databases, 487 Blob_trheshold
for replication, 478, 482, 503 replication option, 543
SQL Remote, 456 blobs
batch mode replication, 307, 543
Message Agent, 454

680
C–C

columns
C adding to remote MobiLink databases, 115
cache
publishing selected columns, 318
for messages, 459
updating, 608
CALL statement
command-line
scripts, 84
configuration file, 524
cascading deletes
environment variables, 524
during MobiLink synchronization, 46
Message Agent, 524
ccMail
command-line utilities
SQL Remote, 441
dbmlsrv7 syntax, 150
Certicom MobileTrust certificates
dbmlstop syntax, 157
activating transport-layer security with server-
dbmlsync syntax, 161
authentification, 55
dbssrv7 syntax, 150
certificates
dbsstop syntax, 157
for server authentication during MobiLink
gencert syntax, 164
synchronization, 53
mlxtract syntax, 157
generating new elliptic-curve, 164
MobiLink synchronization, 150
reading elliptic-curve, 164
readcert syntax, 164
changes in version
using dbmlsrv7, 40
6.0.2, 220
using dbmlstop, 40
6.0.3, 25, 218
commit
7.0, 23, 217
replication, 302
character sets
commit_state column
compatible, 298
about, 31
conversions, 299
communications faults
MobiLink synchronization, 48
MobiLink synchronization recovery, 34, 44
new features, 25
compatibility
SQL Remote, 299
Adaptive Server Anywhere Adaptive Server
characteristics
Enterprise, 425, 426
MobiLink synchronization, 13
among databases, 298
Replication Server, 14
between Adaptive Server Enterprise Adaptive
SQL Remote, 14
Server Anywhere, 298
character-set translation
compression
by ODBC drivers, 50
messages, 543
during MobiLink synchronization under other
COMPRESSION
platforms, 50
replication option, 543
during MobiLink synchronization under
concurrency
Windows, 48
MobiLink upload-stream processing, 45
choosing a replication technology, 11
configuration file
ciphers
Message Agent options, 524
MobiLink transport-layer security, 51
conflict detection
clients
about, 80, 303, 349, 396
Adaptive Server Anywhere as MobiLink, 31
long data types, 307
MobiLink synchronization, 30
occurrence, 78
MobiLink synchronization Adaptive Server
conflict resolution
Anywhere, 131
#remote, 400
UltraLite applications as MobiLink, 30
about, 80, 109
collation sequences
approaches to, 352, 355
MobiLink synchronization, 48
conflict detection, 109
collations
example, 398, 400
SQL Remote, 299
forcing, 111

681
C–C

implementing, 350, 396 setting up, 248, 257, 276, 286


limitations, 398 SQL Server asMobiLink, 38
manual handling, 111 consolidated permissions
occurrence, 78 managing, 431
triggers, 350, 352, 396 constraints
user-specific logic, 112 the extraction utility, 425
conflicts continuous mode
#remote, 400 Message Agent, 454
about, 313, 347, 349, 394, 396 control statements
approaches to resolving, 352, 355 replication of, 491
avoiding, 312 conventions
detection, 313 documentation, xii
example, 398, 400 conversion
in replications, 312 of data types in MobiLink synchronization, 168
locking, 328, 376 to Adaptive Server Enterprise data types in
not errors, 474, 501 MobiLink synchronization, 168
not in Message Agent output, 474, 501 to IBM DB2 data types in MobiLink
primary key, 357, 360, 405 synchronization, 169
reporting, 355 to Microsoft SQL Server data types in MobiLink
resolving, 350, 352, 396 synchronization, 171
SQL Remote handling of, 349, 396 to Oracle data types in MobiLink
VERIFY_ALL_COLUMNS option, 351 synchronization, 170
connection scripts CREATE PUBLICATION statement
about MobiLink, 65 SQL syntax, 579
defined, 64 CREATE REMOTE MESSAGE TYPE statement
example, 97, 98 SQL syntax, 581
connection-based replication, 8 CREATE statements
connections replication, 306
Message Agent, 455 CREATE SUBSCRIPTION statement
consolidate permissions about, 366, 427
granting, 434, 590 SQL syntax, 583
revoking, 434, 598 CREATE SYNCHRONIZATION DEFINITION
CONSOLIDATE permissions statement
granting, 437 SQL syntax, 197
consolidated database CREATE SYNCHRONIZATION SITE statement
publishing, 599 SQL syntax, 202
revoking permissions, 598 CREATE SYNCHRONIZATION TEMPLATE
consolidated databases, 5 statement
Adaptive Server Enterprise asMobiLink, 38 SQL syntax, 204
adding synchronization scripts to, 68 CREATE TRIGGER statement
creating MobiLink, 38 SQL syntax, 584
defined, 20 creating
IBM DB2 asMobiLink, 38 articles, 317, 324
MobiLink, 35 message types, 442, 443
MobiLink synchronization server requirements MobiLink consolidated databases, 38
for, 35 new elliptic-curve certificates, 164
MobiLink system tables, 36 publications, 317, 579
MobiLink user names, 31 remote message types, 581
Oracle asMobiLink, 38 subscriptions, 366, 583
relating tables to MobiLink remote tables, 36 triggers, 584

682
D–D

creating articles data recovery


column-wise partitioning, 372 SQL Remote, 456
row-wise partitioning, 373 data sources
creating publications, 251, 259, 278, 371 ODBC for MobiLink synchronization, 39
column-wise partitioning, 318, 372 data types
row-wise partitioning, 320, 373 conversion of in MobiLink synchronization, 168
simple publications, 317, 371 conversion to Adaptive Server Enterprise in
using Sybase Central, 371 MobiLink synchronization, 168
creating subscriptions, 252, 259, 279, 289, 411 conversion to IBM DB2 in MobiLink
current publisher synchronization, 169
table for, 558 conversion to Microsoft SQL Server in MobiLink
CURRENT PUBLISHER, 250, 592 synchronization, 171
about, 258 conversion to Oracle in MobiLink
current remote user synchronization, 170
conflict resolution, 400 replication, 307
table for, 558 database extraction
CURRENT REMOTE USER default, 351 starting subscriptions during, 597
cursor scripts database extraction utility
defined, 64 MobiLink, 157
list, 64 Database extraction utility, 532
cursors database schemas
passthrough mode, 491 relating consolidated tables to MobiLink remote
replication and, 491 tables, 36
custase.sql databases
location, 91 consolidated, 5
CustDB application loading data into, 419
source code, 89 MobiLink consolidated, 35
synchronization scripts, 91 MobiLink synchronization server requirements
CustDB database for consolidated, 35
DB2, 90 procedures before extracting, 420
schema, 89 remote, 5, 253, 261, 281
custdb.sqc synchronizing, 261, 262
location, 91 synchronizing with MobiLink, 27
custdb.sql dates
location, 91 replication, 308, 544
custmss.sql DB2
location, 91 as MobiLink consolidated databases, 38
custora.sql consolidated database, 90
location, 91 CustDB database, 90
maximum identifier length in IBM, 37
new features, 25
dbcc settrunc
D using, 505
daemon dbmlsrv7 command-line utility
dbremote, 529 syntax, 150
Message Agent, 529 using, 40
ssremote, 529 dbmlstop command-line utility
data consistency syntax, 157
during replication, 4 using, 40
data integrity
during replication, 4

683
D–D

dbmlsync command-line utility DELETE_OLD_LOGS


permissions, 138 replication option, 543
syntax, 161 DELETE_OLD_LOGS option, 482
using, 138 deletes
dbo user stopping upload of using MobiLink, 147
system objects, 531 deleting
dbremote, 263, 264, 292, 293 message types, 443
about, 522 Deleting Corrupt Message error, 465
command line, 522 deleting rows
Message Agent, 292 synchronization, 74
DBREMOTE deployment
about, 454 of SQL Remote databases, 413, 414, 415
security, 473 design
dbssrv7 command-line utility about, 297, 298
syntax, 150 at the consolidated database, 298
dbsstop command-line utility for Adaptive Server Anywhere, 315
syntax, 157 for Adaptive Server Enterprise, 369
DBUNLOAD for mobile workforces, 322, 374
replication, 488 locking, 328, 376
dbxtract many-to-many example, 338, 342, 386
sp_hook_dbxtract_begin procedure, 359 many-to-many relationships, 338, 386
DBXTRACT, 261 of publications, 327, 376
about, 417, 532 performance, 329
command line, 532 tasks, 370
using, 419 tasks for SQL Remote, 316
DDL statements designing publications, 312, 355, 403, 404
remote MobiLink databases, 115 development tips
replication of, 306 synchronization, 88
SQL Remote, 506 differences
deadlock SQL Remote versions, 669
MobiLink upload-stream processing, 45 directories
debug control parameter executable, xiii
FTP message system, 447 installation, xiii
Debug control parameter Directory control parameter
file message system, 447 file message system, 447
MAPI message system, 452 disconnecting
SMTP message system, 450 from MobiLink synchronization server, 35
VIM message system, 453 disjoint partitioning
debugging defined, 101
MobiLink synchronization server log, 42 synchronization, 101
default_download_cursor script documentation
about, 70 conventions, xii
default_upload_cursor script download stream
about, 70 defined, 32
defaults events, 76
the extraction utility, 425 indexes, 93
definitions performance, 93
MobiLink synchronization, 134 download_cursor script
DELETE statement about, 64, 72
replication of, 302 example, 58, 91, 99

684
E–E

download_cursor table script e-mail, 8


MobiLink syntax, 177 MAPI, 441
download_cursor-script SMTP, 441
performance, 93 VIM, 441
download_delete_cursor script encoding
about, 64, 74 about, 465
download_delete_cursor table script custom, 466
MobiLink syntax, 178 encryption
download_delete_cursor-script during MobiLink synchronization, 51
performance, 93 of messages, 457
downloading rows end_connection connection script
synchronization scripts, 72 MobiLink syntax, 179
DROP PUBLICATION statement end_connection event
about, 325 occurrence, 62
SQL syntax, 587 end_download connection script
DROP REMOTE MESSAGE TYPE statement MobiLink syntax, 179
SQL syntax, 588 end_download event
DROP SUBSCRIPTION statement occurrence, 76
SQL syntax, 589 end_download table script
DROP SYNCHRONIZATION DEFINITION MobiLink syntax, 180
statement end_download_deletes event
SQL syntax, 206 occurrence, 76
DROP SYNCHRONIZATION SITE statement end_download_deletes table script
SQL syntax, 206 MobiLink syntax, 180
DROP SYNCHRONIZATION TEMPLATE end_download_rows event
statement occurrence, 76
SQL syntax, 207 end_download_rows table script
dropping MobiLink syntax, 180
message types, 443, 444 end_synchronization connection script
publications, 587 MobiLink syntax, 181
remote message types, 588 end_synchronization event
subscriptions, 589 occurrence, 62
dropping publications, 325 end_synchronization table script
dropping users MobiLink syntax, 181
consolidate, 598 end_upload connection script
dsi_num_threads MobiLink syntax, 182
Replication Server parameter, 517 end_upload event
dsi_sql_data_style parameter occurrence, 78
configuring, 518 end_upload table script
dumps MobiLink syntax, 182
coordinating, 519 end_upload_deletes table script
MobiLink syntax, 183
end_upload_rows event
occurrence, 78
E end_upload_rows table script
elliptic-curve certificates MobiLink syntax, 183
generating new, 164 environment variable
reading, 164 Message Agent options, 524
environment variables
SQLREMOTE, 445

685
F–G

error handling, 474, 501 purpose, 423


about, 475, 501 using from Sybase Central, 421
action codes, 81
default, 474, 501
during MobiLink synchronization, 81
ignoring errors, 474 F
error messages faults
handle_error script, 81 MobiLink synchronization recovery, 34, 44
errors features
conflicts are not, 474, 501 MobiLink synchronization compared, 11
handling, 475, 501 FILE message type
handling during MobiLink synchronization, 81 about, 578
ignoring, 474 FILE messages
in SQL statements, 313 about, 581, 588
multiple, 83 file sharing
notification, 475, 501 control parameters, 447
primary key, 312 message system, 441
recording, 82 message types, 446
reporting, 474, 501 Fire_triggers option
types of in replication, 312 trigger actions, 306
event names FOR UPDATE clause
defined, 58 SELECT statement, 77
events Force_Download control parameter
synchronization events, 62 MAPI message system, 452
synchronization scripts and, 58 forcing conflicts, 111
example_download_cursor script foreign keys
about, 70 publications, 327, 330, 376, 378, 381
example_upload_cursor script territory realignment, 333, 334, 380
about, 70 frequency
examples of sending, 436
synchronization scripts, 70 of sending messages, 590, 593
executable directory ftp
about, xiii control parameters, 447
extraction message types, 447
custom procedures, 422 troubleshooting, 448
designing a procedure, 422 ftp message type, 441
of databases, 413, 414, 417 about, 578
of many databases, 422 FTP messages
operating systems, 417 about, 581
performance, 384, 391
procedures before, 420
reload files, 419
using Sybase Central, 421 G
extraction utility, 419 gencert command-line utility
about, 417, 425, 426 syntax, 164
for Adaptive Server Enterprise, 425, 426 generating
groups, 423 new elliptic-curve certificates, 164
limits, 423 unique column values, 357
MobiLink, 157 global autoincrement
options, 546 using to generate unique values, 357
procedures before using, 420

686
H–L

GLOBAL_DATABASE_ID option icons


setting, 359 used in the manuals, xiii
GRANT CONSOLIDATE statement, 434 identifiers
SQL syntax, 590 maximum length in IBM DB2, 37
GRANT PUBLISH, 249, 257 IF statement
GRANT PUBLISH statement, 431, 432, 433 passthrough mode, 491
SQL syntax, 592 replication of, 491
GRANT REMOTE, 249, 257 IF UPDATE clause
GRANT REMOTE DBA statement in triggers, 584
SQL syntax, 595 IMAGE data type
GRANT REMOTE statement, 434 replication, 307
SQL syntax, 593 initiating
granting MobiLink synchronization from Adaptive Server
consolidate permissions, 590 Anywhere clients, 31
publish permissions, 592 MobiLink synchronization from UltraLite
remote DBA permissions, 595 applications, 30
remote permissions, 593 INSERT statement
granting consolidate permissions, 434 replication of, 302
granting publish permissions, 431, 432, 433 installation directory
granting remote permissions, 434 about, xiii
groups international
extracting, 423, 533 character set support, 299
Internet
e-mail, 449
SQL Remote, 449
H IPM_Receive control parameter
handle_error event MAPI message system, 452
occurrence, 62 IPM_Send control parameter
synchronization scripts, 81 MAPI message system, 452
handle_error script
MobiLink syntax, 183
parameters, 81
Hewlett Packard HP-UX J
availability on, 677 joins
hierarchical database configurations, 5 updates, 608
host control parameter updates based on, 609
FTP message system, 447
HotSync
MobiLink synchronization, 22
L
l option
Message Agent, 457
I laptop computers, 229
IBM AIX replication, 229
availability on, 677 SQL Remote, 229
IBM DB2 library functions
as MobiLink consolidated databases, 38 ULSynchronize, 30
conversion of data types in MobiLink limitations
synchronization, 169 conflict resolution, 398
maximum identifier length in, 37 Enterprise to Enterprise, 672
new features, 25 loading databases, 419

687
M–M

locking media failure


in a replications system, 328, 376 SQL Remote, 456
publication design, 357, 360, 405 Message Agent, 223, 263, 264, 292, 293
log management about, 454, 499
SQL Remote, 456 batch mode, 454
log transfer interface command line, 522
the Message Agent, 505 connections, 455
logging continuous mode, 454
MobiLink synchronization server actions, 42 delivering messages, 467, 469
LONG BINARY -l option, 457
replication, 307 -m option, 459
LONG BINARY data type message tracking, 467, 469
replication, 307 output, 474, 501
LONG VARCHAR performance, 458, 462
replication, 307 polling, 460
LONG VARCHAR data type -rd option, 460
replication, 307 resend requests, 460
LOOP statement -rp option, 460, 461
passthrough mode, 491 running, 472
Lotus Notes running as a service, 472
SQL Remote, 441, 452, 453 schema changes, 506
LTM security, 457, 473, 499
SQL Remote, 495 settings, 457
SQL Remote administration, 430
starting, 472
subscription processing, 311
M threading, 458
m option transaction log management, 478, 482, 487, 503
Message Agent, 459 trigger replication, 306
maintenance releases -u switch, 456
upgrading, 415 user IDs, 499
managing using, 292
synchronization scripts with Sybase Central, 68 worker threads, 458
manual conflict resolution, 111 message control parameters
many-to-many relationships setting, 602
example, 338, 341, 386, 387 message link parameters, 445
partitioning, 102 External_remote_options replication option, 543
publication design, 338, 386 message links
Subscribe_by_remote option, 345, 393 supported, 676
synchronization, 102 message systems
territory realignment, 342 MAPI, 451, 452
triggers for, 343 SMTP, 450
MAPI SQL Remote administration, 430
control parameters, 451, 452 supported, 676
MAPI message type VIM, 452, 453
about, 578 message tracking
MAPI messages SQL Remote administration, 430
about, 581, 588 message types
MAPI system, 441 about, 441
marker SQL Remote table altering, 442, 443
about, 559 creating, 442, 443

688
M–M

dropping, 443, 444 mobile workforces, 227, 229


editing properties, 442 publication design, 322, 374
file sharing, 446, 447 MobileTrust certificates
ftp, 447 activating transport-layer security with server-
parameters, 445 authentification, 55
working with, 442 MobiLink
message-based replication, 8 stopping upload of deletes, 147
messages tables, 167
altering remote types, 578 MobiLink consolidated databases
caching, 459 Adaptive Server Enterprise as, 38
compression, 465, 543 IBM DB2 as, 38
controlling size, 307 Oracle as, 38
creating remote types, 581 SQL Server as, 38
custom encoding, 466 MobiLink databases
delivering, 467, 469 consolidated, 35
dropping remote types, 588 MobiLink download stream
encoding, 465 defined, 32
in SQL Remote, 467, 469 MobiLink synchronization
receiving, 264, 293 a tutorial, 117
resending, 460 about, 3, 19, 27
sending, 264, 292, 293 activating transport-layer security with
synchronizing databases, 427 MobileTrust server-authentification
tracking, 467, 469 certificates, 55
Microsoft Exchange Adaptive Server Anywhere clients, 31, 131
profile, 452 benefits, 4
Microsoft SQL Server character sets, 48
as MobiLink consolidated databases, 38 characteristics, 13
conversion of data types in MobiLink character-set translation on other platforms, 50
synchronization, 171 character-set translation under Windows, 48
missing messages clients, 30
about, 461 command-line utilities, 150
ml_add_connection_script stored procedure consolidated databases, 5
SQL syntax, 190 conversion of data types in, 168
ml_add_connection_script system procedure conversion to Adaptive Server Enterprise data
about, 69 types in, 168
ml_add_table_script stored procedure conversion to IBM DB2 data types in, 169
SQL syntax, 190 conversion to Microsoft SQL Server data types
ml_add_table_script system procedure in, 171
about, 69 conversion to Oracle data types in, 170
ml_connection_script table definitions, 134
about, 36 extracting a database, 157
ml_script table fault recovery, 34, 44
about, 36 features compared, 11
ml_table table hierarchical database configurations, 5
about, 36 initiating from Adaptive Server Anywhere
ml_table_script table clients, 31
about, 36 initiating from UltraLite applications, 30
ml_user table logging server actions, 42
about, 31, 36 mlxtract command-line utility, 157
mlxtract command-line utility ODBC data sources for, 39
syntax, 157 parts of the system, 28

689
N–O

performance, 45
process details, 43
N
named constraints
process overview, 32
the extraction utility, 425
recovery, 31
named defaults
referential integrity during, 46
the extraction utility, 425
running servers as Windows services, 41
NCHAR data type
scripts, 29, 173
the extraction utility, 425
server authentication, 53
NetWare
SQL statements, 192
SQL Remote, 447
starting servers, 40
supported message systems, 441
steps, 33
new features
stopping servers, 40
version 6.0.2, 220
stopping the server, 157
version 6.0.3, 25, 218
stored procedures, 190
version 7.0, 23, 217
streams, 22
new_row_cursor
synchronizing Adaptive Server Anywhere
storing user name, 112
clients, 161
new_row_cursor event
system tables, 36
occurrence, 78
techniques, 85
new_row_cursor table script
timestamps in, 43
MobiLink syntax, 184
transactional and data integrity, 4
Notes
transactions during, 43
SQL Remote, 441, 452
transport-layer security with, 51
Novell NetWare
two-way, 7
availability on, 677
UltraLite clients, 30
NUMBER function
user names, 31
updates, 609
versions of scripts, 67
NVARCHAR data type
writing scripts, 57
the extraction utility, 425
MobiLink synchronization server
disconnecting from, 35
new features, 25
requirements for consolidated databases, 35
MobiLink synchronization servers
O
object SQL Remote table
about, 29 about, 560
starting, 150
ODBC
MobiLink synchronization upload stream multiple errors, 83
processing, 45 ODBC data sources
MobiLink system tables for MobiLink synchronization, 39
creating in consolidated database, 38
ODBC drivers
MobiLink upload stream MobiLink character-set translation by, 50
defined, 32 offsets
mobilink.crt, 53 in transaction log, 467
multiple applications
old_row_cursor
differentiating MobiLink scripts, 67 storing user name, 112
multi-tier installations old_row_cursor event
passthrough statements, 491 occurrence, 78
permissions, 439
old_row_cursor table script
MobiLink syntax, 185
operating systems
availability on, 677
supported, 675

690
P–P

option SQL Remote table passwords


about, 560 saving, 544
options the extraction utility, 425
setting remote, 602 Path control parameter
Subscribe_by_remote, 345, 393 VIM message system, 453
the extraction utility, 546 patience
Verify_threshold, 307 Message Agent, 461
Oracle performance
as MobiLink consolidated databases, 38 benefits of replication, 4
conversion of data types in MobiLink concurrency, 93
synchronization, 170 database extraction, 422
overlaps design tips, 329
partitioning, 101 download_cursor script, 93
download_delete_cursor script, 93
downloads, 93
incoming messages, 460
P indexes, 93
parameters Message Agent, 458
primary keys, 65 message sending, 462
synchronization scripts, 65 MobiLink upload stream processing, 45
synchronization user name, 65 network speed, 93
table name, 65 number of subscriptions, 311
partitioning publications, 310
column-wise, 318, 372 replication throughput, 458
defined, 101 replication turnaround time, 458
disjoint, 101 SQL Remote, 458
row-wise, 320, 373 ssxtract, 384, 391
partitioning tables synchronization, 93
example, 101 threading, 458
passthrough mode updates, 610
Adaptive Server Enterprise, 507 permissions
batches, 491 consolidate, 434
for Adaptive Server Anywhere, 489 CONSOLIDATE, 590
operations not replicated, 491 granting consolidate, 590
operations not replicated in, 491 granting CONSOLIDATE, 437
starting, 596 granting publish, 592
stopping, 596 granting remote, 593
uses, 490 granting remote DBA, 595
passthrough SQL Remote table multi-tier installations, 439
about, 560 publish, 249, 257, 431, 432, 433
PASSTHROUGH statement remote, 249, 257, 434
SQL syntax, 596 revoking consolidate, 598
using, 489 revoking publish, 599
passthrough statements revoking remote, 600
multi-tier installations, 491 revoking REMOTE, 438
password control parameter revoking remote DBA, 601
FTP message system, 447 SQL Remote administration, 430
Password control parameter platforms
VIM message system, 453 supported operating systems, 675
polling
messages, 460

691
P–P

pop3_host control parameter protocols


SMTP message system, 450 MobiLink synchronization, 28
pop3_password control parameter MobiLink synchronization streams, 22
SMTP message system, 450 publication design
pop3_userid control parameter for Adaptive Server Anywhere, 315
SMTP message system, 450 for Adaptive Server Enterprise, 369
port control parameter for many subscribers, 322, 374
FTP message system, 447 using subscription expression, 322, 374
primary key errors publication SQL Remote table
about, 312 about, 561
primary key pool publication table
about, 405 about, 549
primary key pools publications
about, 405 about, 225
replenishing, 407 altering, 324, 577
replicating, 406 column-wise partitioning, 318, 372
summary, 410 creating, 251, 259, 278, 317, 371, 579
primary keys creating using Sybase Central, 371
generating unique values, 357 design at consolidated database, 316
generating unique values using pools, 360 designing, 297, 298, 312, 327, 355, 376, 403,
in publications, 302 404, 610
primary-key pools, 106 dropping, 325, 587
publications, 327, 376 example, 267
replication, 355, 404 foreign keys, 327, 330, 376, 378
replication and, 357 locking, 328, 376
SQL Remote, 355, 404 managing subscriptions, 366
uniqueness, 105, 405 many-to-many example, 338, 341, 342, 386, 387
primary-key pools many-to-many relationships, 338, 386
example, 106 notes, 326
generating unique values using default global performance, 310, 329
autoincrement, 357 primary keys, 327, 355, 357, 360, 376, 404, 405
replenishing, 362 properties, 317
replicating, 361 referential integrity, 355, 403
summary, 364 row-wise partitioning, 320, 373
synchronization, 105 setting up, 317, 371
procedure groups simple, 317, 371
the extraction utility, 425 subqueries, 330
procedures tables in many publications, 310
passthrough mode, 491 transactions, 328, 376
replicating, 304 updates, 610
SQL Remote, 304 using a WHERE clause, 321, 373
SQL Remote Open Server, 519 whole tables, 319
statements corresponding to, 670 publications SQL Remote view
profiles about, 566
Microsoft Exchange, 452 publications view
properties about, 554
articles, 317 publish permissions, 249, 257
message type properties, 442 granting, 431, 432, 433, 592
publications, 317 managing, 431
remote permissions, 249, 257
revoking, 431, 432, 433, 599

692
Q–R

publisher, 250 reload files


about, 431, 432, 433 database extraction, 419
adding to a database, 258 remote databases, 5
address, 442, 581, 588 remote permissions, 434
creating, 431, 432, 433 setting up, 253, 261, 262, 281
GRANT PUBLISH statement, 592 remote DBA permissions
remote, 593 granting, 595
publisher SQL Remote table revoking, 601
about, 561 REMOTE DBA permissions
publishers MobiLink synchronization, 138
addresses, 578 revoking, 601
publishing remote message types
selected columns, 318 altering, 578
whole table, 317 creating, 581
dropping, 588
remote options
setting, 602
Q remote permissions
Qualify_owners granting, 434, 593
replication option, 543 managing, 431
quiet system revoking, 434, 438, 600
definition, 506 Sybase Central, 435
Quote_all_identifiers REMOTE RESET statement
replication option, 543 SQL syntax, 597
remote users
REVOKE REMOTE statement, 600
remoteoption table
R about, 550
readcert command-line utility remoteoptions SQL Remote view
syntax, 164 about, 555, 567
reading remoteoptiontype table
elliptic-curve certificates, 164 about, 550
Receive_all control parameter remotetable table
VIM message system, 453 about, 562
receiving messages, 264, 293 remotetables SQL Remote view
recording errors during synchronization, 82 about, 567
recovery remotetype SQL Remote table
SQL Remote, 456 about, 562
reference remotetype table
MobiLink SQL statements, 192 about, 550
MobiLink stored procedures, 190 remotetypes SQL Remote view
MobiLink synchronization command-line about, 567
utilities, 150 remoteuser SQL Remote table
MobiLink synchronization scripts, 173 about, 563
referential integrity remoteuser table, 467
during MobiLink synchronization, 46 about, 551
replication, 355, 403 remoteusers SQL Remote view
SQL Remote, 355, 403 about, 568
registry remoteusers view
SQL Remote, 445 about, 555
replicating procedures, 304

693
R–R

replicating triggers, 305 replication conflicts


replication about, 347, 394
about, 3 replication definitions
administering, 227 Replication Server, 517
backup procedures, 478, 482, 487, 503 replication options
benefits, 4 Qualify_owners, 543
blobs, 307 Quote_all_identifiers, 543
by e-mail, 8 REPLICATION_ERROR, 313, 475, 501, 544
case studies, 229, 231 SUBSCRIBE_BY_REMOTE, 545
conflicts, 312 VERIFY_THRESHOLD, 545
connection-based, 8 replication role
data definition statements, 306 granting, 499
data types, 307 Replication Server
design, 327, 376 characteristics, 14
designing, 327, 376 configuring, 517
hierarchical database configurations, 5 restart the connection, 518
message-based, 8 SQL Remote, 495, 509, 510, 517
mobile workforces, 229 SQL Remote architecture, 511
MobiLink synchronization definitions, 134 ssqueue, 514
of control statements, 491 using SQL Remote with, 539
of cursor operations, 491 REPLICATION_ERROR
of cursor statements, 491 replication option, 313, 475, 501, 544
of procedures, 304 report_error script
of SQL statements, 489 MobiLink syntax, 187
of stored procedures, 491 syntax, 82
options, 542 reporting
passthrough mode, 489 conflicts, 355
primary key errors, 404 reporting errors, 474, 501
primary keys, 357, 360, 405 reporting errors during synchronization, 82
primary-key errors, 355 requirements
publications, 225 for MobiLink consolidated databases, 35
referential integrity errors, 355, 403 resend requests
server-to-laptop replication, 229 about, 461
server-to-server, 231 messages, 460
setup examples, 229 resetting
subscriptions, 225 subscriptions, 663
transaction log, 302 RESOLVE UPDATE triggers, 350, 352
transaction log and, 227 resolve_conflict event
transaction log management, 478, 482, 487, 503 occurrence, 78
transactional and data integrity, 4 resolve_conflict table script
triggers, 305, 356 MobiLink syntax, 187
two-way, 7 REVOKE CONSOLIDATE statement, 434
upgrading databases, 487 SQL syntax, 598
Replication, 532 REVOKE PUBLISH statement, 431, 432, 433
dbremote, 522 SQL syntax, 599
Message Agent, 522 REVOKE REMOTE DBA statement
ssqueue, 539 SQL syntax, 601
ssremote, 522 REVOKE REMOTE statement, 434, 438
synchronization, 532 SQL syntax, 600
Replication Agent
SQL Remote, 495, 510, 511

694
S–S

revoking security
consolidate permissions, 598 during MobiLink synchronization, 51
publish permissions, 599 MobiLink client architecture, 54
remote DBA permissions, 601 MobiLink synchronization, 138
remote permissions, 600 replication, 595, 601
revoking consolidate permissions, 434 SELECT statement
revoking publish permissions, 431, 432, 433 FOR UPDATE clause, 77
revoking remote permissions, 434, 438 SEND AT
roles frequency setting, 436
the extraction utility, 425 SEND AT clause, 590, 593
root control parameter publish, 592
FTP message system, 447 SEND EVERY
rows frequency setting, 436
partitioning, 101 SEND EVERY clause, 590, 593
rs_dumpdb send frequency
using, 519 selecting, 436
rs_dumptran the Message Agent, 454
using, 519 Send_VIM_Mail control parameter
running VIM message system, 453
the Message Agent, 472 sending messages, 264, 292, 293
server authentication
during MobiLink synchronization, 53
servers
S about MobiLink synchronization, 29
sample application starting MobiLink synchronization, 150
source code, 89 server-to-server replication, 231
synchronization scripts, 91 services
sample database Message Agent as, 472
schema, 89 running MobiLink synchronization servers as
Save_remote_passwords Windows, 41
replication option, 544 SET REMOTE OPTION statement
schema changes SQL syntax, 602
remote MobiLink databases, 115 setting
SQL Remote, 506 remote options, 602
SQL Remote Open Server, 519 setting up a remote database, 253, 261, 281
schemas setting up publications, 317, 371
relating consolidated tables to MobiLink remote setting up subscriptions, 366, 411
tables, 36 setting up the consolidated database, 248, 257, 276,
ScoutSync 286
MobiLink synchronization, 22 setup
script versions SQL Remote, 233
in MobiLink synchronization, 67 SQL Remote Adaptive Server Enterprise, 235
scripts SQL Remote overview, 234
in MobiLink system tables, 36 SQL Remote stable queue, 237
MobiLink synchronization, 29, 173 TEMPDB for SQL Remote, 235
secure-socket layer Silicon Graphics IRIX
with MobiLink synchronization, 51 availability on, 677
secure-socket layers SMTP
activating with MobileTrust server- control parameters, 450
authentification certificates, 55 e-mail, 449
SQL Remote, 449

695
S–S

SMTP message type, 441 sp_passthrough_piece procedure


SMTP/POP about, 507
addresses, 451 syntax, 633
smtp_host control parameter sp_passthrough_stop procedure
SMTP message system, 450 about, 507
snapshot synchronization, 94 syntax, 635
example, 95 sp_passthrough_subscription procedure
software about, 507
dbremote, 522 syntax, 636
DBXTRACT, 532 sp_passthrough_user procedure
ssqueue, 539 about, 507
ssremote, 522 syntax, 637
SSXTRACT, 532 sp_populate_sql_anywhere procedure
sort order of characters about, 426
MobiLink synchronization, 48 sp_publisher procedure
source code syntax, 639
CustDB application, 89 sp_queue_clean procedure
sp_ procedure syntax, 640
syntax, 638 sp_queue_confirmed_delete_old procedure
sp_add_article procedure syntax, 641
syntax, 613 sp_queue_confirmed_transaction procedure
sp_add_article_col procedure syntax, 642
syntax, 615 sp_queue_delete_old procedure
sp_add_remote_table procedure syntax, 643
syntax, 616 sp_queue_drop procedure
sp_connection_script stored procedure syntax, 644
SQL syntax, 190 sp_queue_dump_database procedure
sp_create_publication procedure syntax, 645
syntax, 618 sp_queue_dump_transaction procedure
sp_drop_publication procedure syntax, 646
syntax, 619 sp_queue_get_state procedure
sp_drop_remote_type procedure syntax, 647
syntax, 620 sp_queue_log_transfer_reset procedure
sp_drop_sql_remote procedure syntax, 648
syntax, 621 sp_queue_read procedure
sp_grant_consolidate procedure syntax, 649
syntax, 622 sp_queue_reset procedure
sp_grant_remote procedure syntax, 650
syntax, 624 sp_queue_set_confirm procedure
sp_hook_dbxtract_begin procedure syntax, 651
unique primary keys, 359 sp_queue_set_progress procedure
using, 359 syntax, 652
sp_link_option procedure sp_queue_transaction procedure
syntax, 626 syntax, 653
sp_modify_article procedure sp_remote procedure
syntax, 628 syntax, 654
sp_modify_remote_table procedure sp_remote_option procedure
syntax, 630 syntax, 655
sp_passthrough procedure sp_remote_type procedure
about, 507 syntax, 656
syntax, 632

696
S–S

sp_remove_article procedure granting publish permissions, 249, 257


syntax, 657 granting remote permissions, 249, 257
sp_remove_article_col procedure Message Agent, 223, 263, 264, 292, 293
syntax, 658 message delivery, 467, 469
sp_remove_remote_table procedure message tracking, 467, 469
syntax, 659 mobile workforces, 227, 229
sp_revoke_consolidate procedure multi-tier installations, 491
syntax, 660 options, 542
sp_revoke_remote procedure passthrough mode, 596
syntax, 661 publications, 225
sp_setreplicate procedure publish permissions, 599
sp_add_remote_table, 616 remote databases, 5
sp_subscription procedure remote permissions, 593, 600
about, 411 remote reset, 597
syntax, 662 server-to-laptop replication, 229
using, 427 server-to-server replication, 231
sp_subscription_reset procedure setting remote options, 602
syntax, 663 setting up, 245, 255, 273, 283
sp_table_script stored procedure setting up a consolidated database, 248, 257, 276,
SQL syntax, 190 286
sp_user_extraction_hook setting up a remote database, 253, 261, 281
example, 390 setup, 234
sp_user_extraction_hook procedure setup examples, 229
about, 426 ssremote, 293
SQL Remote SSXTRACT utility, 532
about, 221 starting subscriptions, 604
Adaptive Server Enterprise setup, 235 stopping subscriptions, 606
administering, 227, 490 subscribers, 227
ALTER REMOTE MESSAGE TYPE statement, subscriptions, 225
578 synchronization, 532
altering publications, 577 synchronizing subscriptions, 607
articles, 549, 559 system tables, 549, 559
backup procedures, 478, 482, 487, 503 TEMPDB, 235
case studies, 229, 231 transaction log management, 478, 482, 487, 503
characteristics, 14 tutorial with Adaptive Server Enterprise, 269
consolidate permissions, 590, 598 uninstalling, 621, 644
consolidated databases, 5 unloading databases, 488
CREATE PUBLICATION statement syntax, 579 upgrading, 239
CREATE REMOTE MESSAGE TYPE upgrading databases, 487
statement, 581 user IDs, 499
creating publications, 251, 259, 278, 579 SQL Remote Open Server
creating subscriptions, 583 architecture, 511
dbremote, 263, 264, 292, 293 command line, 539
DBXTRACT utility, 532 IRIX, 677
design tasks, 316 procedures, 519
DROP REMOTE MESSAGE TYPE statement, schema changes, 506
588 setting up, 514
dropping publications, 587 when needed, 510
dropping subscriptions, 589 SQL Remote procedures
extracting a database, 532 sp_, 638
GRANT PUBLISH statement, 592 sp_add_article, 613

697
S–S

sp_add_article_col, 615 remoteoptiontype, 550


sp_add_remote_table, 616 remotetable, 562
sp_create_publication, 618 remotetype, 550, 562
sp_drop_publication, 619 remoteuser, 551, 563
sp_drop_remote_type, 620 sr_remoteoption, 561
sp_drop_sql_remote, 621 sr_remoteoptiontype, 562
sp_grant_consolidate, 622 subscription, 552, 564
sp_grant_remote, 624 SQL Remote system views
sp_link_option, 626 articlecols, 554, 566
sp_modify_article, 628 articles, 554, 566
sp_modify_remote_table, 630 publications, 554, 566
sp_passthrough, 632 remoteoptions, 555, 567
sp_passthrough_piece, 633 remotetables, 567
sp_passthrough_stop, 635 remotetypes, 567
sp_passthrough_subscription, 636 remoteusers, 555, 568
sp_passthrough_user, 637 subscriptions, 556, 569
sp_publisher, 639 SQL Remote tables
sp_queue_clean, 640 #remote, 558
sp_queue_confirmed_delete_old, 641 SQL Server
sp_queue_confirmed_transaction, 642 as MobiLink consolidated databases, 38
sp_queue_delete_old, 643 SQL statements
sp_queue_drop, 644 ALTER PUBLICATION syntax, 577
sp_queue_dump_database, 645 ALTER REMOTE MESSAGE TYPE syntax,
sp_queue_dump_transaction, 646 578
sp_queue_get_state, 647 ALTER SYNCHRONIZATION DEFINITION
sp_queue_log_transfer_reset, 648 syntax, 192
sp_queue_read, 649 ALTER SYNCHRONIZATION SITE syntax,
sp_queue_reset, 650 194
sp_queue_set_confirm, 651 ALTER SYNCHRONIZATION TEMPLATE
sp_queue_set_progress, 652 syntax, 195
sp_queue_transaction, 653 CREATE PUBLICATION syntax, 579
sp_remote, 654 CREATE REMOTE MESSAGE TYPE syntax,
sp_remote_option, 655 581
sp_remote_type, 656 CREATE SUBSCRIPTION syntax, 583
sp_remove_article, 657 CREATE SYNCHRONIZATION DEFINITION
sp_remove_article_col, 658 syntax, 197
sp_remove_remote_table, 659 CREATE SYNCHRONIZATION SITE syntax,
sp_revoke_consolidate, 660 202
sp_revoke_remote, 661 CREATE SYNCHRONIZATION TEMPLATE
sp_subscription, 662 syntax, 204
sp_subscription_reset, 663 CREATE TRIGGER syntax, 584
SQL Remote system tables DROP PUBLICATION syntax, 587
article, 548, 558 DROP REMOTE MESSAGE TYPE syntax, 588
articlecol, 549, 559 DROP SUBSCRIPTION syntax, 589
marker, 559 DROP SYNCHRONIZATION DEFINITION
object, 560 syntax, 206
option, 560 DROP SYNCHRONIZATION SITE syntax, 206
passthrough, 560 DROP SYNCHRONIZATION TEMPLATE
publication, 549, 561 syntax, 207
publisher, 561 GRANT CONSOLIDATE syntax, 590
remoteoption, 550 GRANT PUBLISH syntax, 592

698
S–S

GRANT REMOTE DBA syntax, 595 sr_queue_coordinate table


GRANT REMOTE syntax, 593 about, 573
MobiLink synchronization, 192 sr_queue_state table
PASSTHROUGH syntax, 596 about, 570
REMOTE RESET syntax, 597 sr_remoteoption table
replication, 306 about, 561
replication of, 302, 303 sr_remoteoptiontype table
REVOKE CONSOLIDATE syntax, 598 about, 562
REVOKE PUBLISH syntax, 599 sr_remotetable table
REVOKE REMOTE DBA syntax, 601 about, 562
REVOKE REMOTE syntax, 600 sr_remotetype table
SET REMOTE OPTION syntax, 602 about, 562
START SUBSCRIPTION syntax, 604 sr_remoteuser table
START SYNCHRONIZATION DELETE about, 563
syntax, 208 sr_subscription table
STOP SUBSCRIPTION syntax, 606 about, 564
STOP SYNCHRONIZATION DELETE syntax, sr_transaction table
208 about, 572
SYNCHRONIZE SUBSCRIPTION syntax, 607 ssqueue
UPDATE syntax, 608 about, 509, 539
SQL syntax architecture, 511
ml_add_connection_script stored procedure, 190 command line, 539
ml_add_table_script stored procedure, 190 IRIX, 677
SQLANY.INI setting up, 514
SQL Remote, 445 when needed, 510
SQLCODE ssremote, 293
handle_error script, 81 about, 522
SQLRemote environment variable, 445 command line, 522
SQLREMOTE environment variable SSREMOTE
alternative to, 447 about, 454, 499
squpdate.sql security, 499
upgrading the stable queue, 239 ssremote.sql
sr_article table SQL Remote setup, 236
about, 558 ssupdate.sql
sr_articlecol table upgrading SQL Remote, 239
about, 559 ssxtract
sr_confirmed_transaction table about, 417
about, 573 using, 419
sr_marker table SSXTRACT
about, 559 about, 532
sr_object table command line, 532
about, 560 using, 425, 426
sr_option table stable queue
about, 560 cleaning, 525
sr_passthrough table Replication Server, 512
about, 560 setup, 237
sr_publication table SQL Remote Open Server, 512
about, 561 ssqueue, 512
sr_publisher table system tables, 570
about, 561 stableq.sql
SQL Remote setup, 237

699
S–S

START SUBSCRIPTION statement GRANT CONSOLIDATE statement SQL


SQL syntax, 604 syntax, 590
START SYNCHRONIZATION DELETE statement GRANT PUBLISH statement SQL syntax, 592
SQL syntax, 208 GRANT REMOTE DBA statement SQL syntax,
starting 595
MobiLink synchronization from Adaptive Server GRANT REMOTE statement SQL syntax, 593
Anywhere clients, 31 MobiLink synchronization, 192
MobiLink synchronization from UltraLite PASSTHROUGH statement SQL syntax, 596
applications, 30 REMOTE RESET statement SQL syntax, 597
MobiLink synchronization servers, 40, 150 replication of, 302, 303
passthrough mode, 596 REVOKE CONSOLIDATE statement SQL
subscriptions, 604 syntax, 598
subscriptions during database extraction, 597 REVOKE PUBLISH statement SQL syntax, 599
the Message Agent, 472 REVOKE REMOTE DBA statement SQL
statements syntax, 601
ALTER PUBLICATION statement SQL syntax, REVOKE REMOTE statement SQL syntax, 600
577 SET REMOTE OPTION statement SQL syntax,
ALTER REMOTE MESSAGE TYPE statement 602
SQL syntax, 578 START SUBSCRIPTION statement SQL syntax,
ALTER SYNCHRONIZATION DEFINITION 604
statement SQL syntax, 192 START SYNCHRONIZATION DELETE
ALTER SYNCHRONIZATION SITE statement statement SQL syntax, 208
SQL syntax, 194 STOP SUBSCRIPTION statement SQL syntax,
ALTER SYNCHRONIZATION TEMPLATE 606
statement SQL syntax, 195 STOP SYNCHRONIZATION DELETE
CREATE PUBLICATION statement SQL statement SQL syntax, 208
syntax, 579 SYNCHRONIZE SUBSCRIPTION statement
CREATE REMOTE MESSAGE statement SQL SQL syntax, 607
syntax, 581 UPDATE statement SQL syntax, 608
CREATE SUBSCRIPTION statement SQL STOP SUBSCRIPTION statement
syntax, 583 SQL syntax, 606
CREATE SYNCHRONIZATION DEFINITION STOP SYNCHRONIZATION DELETE statement
statement SQL syntax, 197 SQL syntax, 208
CREATE SYNCHRONIZATION SITE stopping
statement SQL syntax, 202 MobiLink synchronization servers, 40
CREATE SYNCHRONIZATION TEMPLATE passthrough mode, 596
statement SQL syntax, 204 stopping subscriptions, 606
CREATE TRIGGER statement SQL syntax, 584 stopping upload of deletes using MobiLink, 147
DROP PUBLICATION statement SQL syntax, store-and-forward, 8
587 stored procedures
DROP REMOTE MESSAGE TYPE statement calling in scripts, 84
SQL syntax, 588 ml_add_connection_script SQL syntax, 190
DROP SUBSCRIPTION statement SQL syntax, ml_add_table_script SQL syntax, 190
589 MobiLink synchronization, 190
DROP SYNCHRONIZATION DEFINITION passthrough mode, 491
statement SQL syntax, 206 replication of, 304
DROP SYNCHRONIZATION SITE statement SQL Remote Open Server, 519
SQL syntax, 206 using to add synchronization scripts, 68
DROP SYNCHRONIZATION TEMPLATE storing user name during conflict resolution, 112
statement SQL syntax, 207 streams
MobiLink synchronization, 22

700
S–S

subqueries Sybase Central


in SQL Remote, 330 creating publications with, 371
publications, 330 extraction utility, 421
SUBSCRIBE BY clause, 579 managing synchronization scripts with, 68
SUBSCRIBE_BY_REMOTE message types, 443
replication option, 545 symbols
Subscribe_by_remote option icons used in the manuals, xiii
many-to-many relationships, 345, 393 syncasa.sql
subscription expressions about, 69
about, 322, 374 syncase.sql
cost of evaluating, 310 about, 69
in the transaction log, 310 syncdb2.sql
many-valued, 310 about, 69
subqueries, 330 synchronization
subscription SQL Remote table a MobiLink tutorial, 117
about, 564 about, 417
subscription table about MobiLink, 3, 19, 27
about, 552 activating transport-layer security with
subscription views MobileTrust server-authentification
about, 391 certificates, 55
subscription-list columns Adaptive Server Anywhere clients MobiLink,
about, 381 131
in SQL Remote, 378 Adaptive Server Anywhere MobiLink clients, 31
maintaining, 383, 388, 390 command-line utilities MobiLink, 150
triggers, 388 conflict resolution, 109
triggers for, 383 conversion of data types in MobiLink, 168
subscriptions, 366 conversion to Adaptive Server Enterprise data
about, 225 types in MobiLink, 168
creating, 252, 259, 279, 289, 366, 411, 583 conversion to IBM DB2 data types in MobiLink,
dropping, 589 169
managing, 366 conversion to Microsoft SQL Server data types in
performance, 311 MobiLink, 171
resetting, 663 conversion to Oracle data types in MobiLink, 170
setting up, 366, 411 DBMS dependencies, 84
starting, 604 deleting rows, 74
starting during database extraction, 597 development tips, 88
stopping, 606 downloading rows, 72
synchronizing, 419, 427, 607 events, 62
the Message Agent, 311 initiating, 138
updates, 610 initiating MobiLink from Adaptive Server
subscriptions SQL Remote view Anywhere clients, 31
about, 569 initiating MobiLink from UltraLite applications,
subscriptions view 30
about, 556 logging MobiLink synchronization server
Sun Solaris actions, 42
availability on, 677 many-to-many relationships, 102
Sybase Adaptive Server Enterprise MobiLink benefits, 4
conversion of data types in MobiLink MobiLink character sets, 48
synchronization, 168 MobiLink characteristics, 13
MobiLink character-set translation under other
platforms, 50

701
S–S

MobiLink character-set translation under synchronization process


Windows, 48 synchronization scripts, 121
MobiLink clients, 30 synchronization scripts
MobiLink consolidated databases, 5 about, 58
MobiLink fault recovery, 34, 44 adding to consolidated database, 59
MobiLink features compared, 11 adding to consolidated databases, 68
MobiLink hierarchical database configurations, 5 adding with stored procedures, 68
MobiLink performance, 45 adding with Sybase Central, 59
MobiLink process details, 43 begin_connection, 173
MobiLink process overview, 32 begin_download, 173
MobiLink recovery, 31 begin_download_deletes, 174
MobiLink referential integrity during, 46 begin_download_rows, 174
MobiLink scripts, 29, 173 begin_synchronization, 175
MobiLink SQL statements, 192 begin_upload, 176
MobiLink steps, 33 begin_upload_deletes, 176
MobiLink stored procedures, 190 begin_upload_rows, 177
MobiLink streams, 22 connection scripts, 64, 65
MobiLink synchronization server authentication, cursor scripts, 64
53 DBMS dependencies, 84
MobiLink system tables, 36 defined, 58
MobiLink transactional and data integrity, 4 download_cursor, 72, 177
MobiLink transactions during, 43 download_delete_cursor, 178
MobiLink user names, 31 end_connection, 179
ODBC data sources for MobiLink, 39 end_download, 179, 180
of databases, 413, 414 end_download_deletes, 180
operating systems, 417 end_download_rows, 180
parts of the MobiLink system, 28 end_synchronization, 181
performance, 93 end_upload, 182
process, 62 end_upload_deletes, 183
running MobiLink synchronization servers as end_upload_rows, 183
Windows services, 41 example, 58
snapshot, 95 examples, 70
starting MobiLink synchronization servers, 40 execution during, 62
starting the MobiLink synchronization server, 40 handle_error, 183
stopping MobiLink synchronization servers, 40 handle_error event, 81
stopping upload of deletes, 147 managing with Sybase Central, 68
techniques, 85 new_row_cursor, 184
timestamp-based, 96 old_row_cursor, 185
timestamps in MobiLink, 43 parameters, 65
transport-layer security with MobiLink, 51 report_error, 82, 187
troubleshooting MobiLink using server log, 42 resolve_conflict, 187
two-way, 7 table scripts, 64, 65
UltraLite MobiLink clients, 30 testing, 70
using DBXTRACT, 419 types, 64
using ssztract, 419 upload_curosr, 77
using the extraction utility, 419 upload_cursor, 188
writing MobiLink scripts, 57 versions in MobiLink, 67
synchronization definitions writing MobiLink, 57
MobiLink, 134 synchronization server
synchronization errors disconnecting from MobiLink, 35
handling MobiLink, 81 stopping, 157

702
T–T

synchronization servers end_download_rows table script, 180


about MobiLink, 29 end_synchronization connection script, 181
starting MobiLink, 40, 150 end_synchronization table script, 181
synchronization techniques end_upload connection script, 182
list, 86 end_upload table script, 182
partitioning, 101 end_upload_deletes table script, 183
primary-key pools, 105 end_upload_rows table script, 183
snapshot-based synchronization, 94 handle_error script, 183
timestamp-based synchronization, 96 mlxtract command-line utility, 157
uploading rows, 77 MobiLink stored procedures, 190
synchronization upload stream MobiLink synchronization command-line
MobiLink processing, 45 utilities, 150
synchronization user name MobiLink synchronization scripts, 173
script parameter, 65 new_row_cursor table script, 184
synchronization utility, 261 old_row_cursor table script, 185
synchronizing Adaptive Server Anywhere report_error script, 187
clients, 161 resolve_conflict table script, 187
SYNCHRONIZE SUBSCRIPTION statement upload_cursor table script, 188
about, 427 SYSREMOTEUSER table, 467
SQL syntax, 607 system objects
synchronizing the dbo user, 531
databases with MobiLink, 27 system tables
synchronizing databases, 261, 262 creating in MobiLink consolidated database, 38
using the message system, 427 MobiLink, 167
synchronizing subscriptions, 607 MobiLink synchronization, 36
syncmss.sql stable queue, 570
about, 69 SYSARTICLE, 549, 559
syncora.sql
about, 69
syntax, 176
begin_connection connection script, 173 T
begin_download connection script, 173 table scripts
begin_download table script, 173 about, 65
begin_download_deletes table script, 174 defined, 64
begin_download_rows table script, 174 tables
begin_synchronization connection script, 175 adding to remote MobiLink databases, 115
begin_synchronization table script, 175 column-wise partitioning, 318, 372
begin_upload connection script, 176 in publications, 319
begin_upload_deletes table script, 176 MobiLink, 167
begin_upload_rows table script, 177 partitioning, 101
dbmlsrv7 command-line utility, 150 publishing, 317, 371
dbmlstop command-line utility, 157 relating consolidated tables to MobiLink remote
dbmlsync command-line utility, 161 tables, 36
dbssrv7 command-line utility, 150 row-wise partitioning, 320, 373
dbsstop command-line utility, 157 updating, 608
download_cursor table script, 177 TCP/IP
download_delete_cursor table script, 178 MobiLink synchronization, 22
end_connection connection script, 179 TEMPDB
end_download connection script, 179 SQL Remote requirements, 235
end_download table script, 180
end_download_deletes table script, 180

703
U–U

territory realignment with Adaptive Server Anywhere MobiLink


about, 383 clients, 54
many-to-many relationships, 342 with MobiLink synchronization, 51
replication of UPDATES, 303 with UltraLite MobiLink clients, 55
subscription-list columns, 381 triggers
triggers for, 343 conflict resolution, 350, 352, 396
territory realignments creating, 584
foreign keys, 333, 334, 380 replicating, 305
testing replication, 335, 356
SQL Remote, 415 replication option, 306
synchronization scripts, 70 RESOLVE UPDATE, 350, 352
TEXT data type SQL Remote, 305, 356
replication, 307 subscription-list columns, 383, 388
threading territory realignment, 334, 335
Message Agent, 458 Watcom-SQL, 584
times troubleshooting
replication, 308, 545 MobiLink synchronization server log, 42
timestamp columns truncation point
the extraction utility, 425 in transaction log, 505
timestamp-based synchronization, 96 setting, 505
example, 96 turnaround time
tips replication performance, 458
synchronization techniques, 88 tutorials
transaction log MobiLink with Adaptive Server Anywhere
Adaptive Server Enterprise, 505 clients, 117
managing, 505 SQL Remote with Adaptive Server Enterprise,
Message Agent, 522 269
message tracking, 467 two-way replication, 7
offsets, 467
publications, 310
replication, 227, 302
scanning, 510 U
SQL Remote, 227, 302, 522 u option
update statements, 310 Message Agent, 456
transaction log mirror ULSynchronize library function, 30
replication, 478, 503 UltraLite applications
transactional integrity as MobiLink clients, 30
during replication, 4 as MobiLink clients with transport-layer security,
transactions 55
during MobiLink synchronization, 43 uncommitted statements
replication, 302 not replicated, 302
translation uninstalling
character-set by ODBC drivers, 50 from a database, 621, 644
translation between character sets unique column values
MobiLink synchronization under other platforms, generating, 357
50 unique primary keys
MobiLink synchronization under Windows, 48 UltraLite installations, 105
transport-layer security unique values
activating with MobileTrust server- generating using default global autoincrement,
authentification certificates, 55 357
MobiLink client architecture, 54 generating using pools, 360

704
V–V

UNIX user names


supported message systems, 441 MobiLink client names, 31
unloading databases Userid control parameter
replication, 488 VIM message system, 453
UPDATE users
IF UPDATE clause, 584 remote, 5
UPDATE conflicts user-specific conflict resolution, 112
about, 347, 394 utilities
UPDATE statement dbmlsrv7 command-line syntax, 150
conflict detection, 307 dbmlstop command-line syntax, 157
for publications, 334 dbmlsync command-line syntax, 161
replication of, 302, 303, 333, 334, 380 dbssrv7 command-line syntax, 150
SQL syntax, 608 dbsstop command-line syntax, 157
territory realignment, 303 gencert command-line syntax, 164
UPDATE statements mlxtract command-line syntax, 157
conflict detection, 303 MobiLink synchronization command-line, 150
updates readcert command-line syntax, 164
information in transaction log, 310 using dbmlsrv7, 40
joins, 609 using dbmlstop, 40
updating
tables and columns, 608
upgrade issues
version 6.0.3, 26, 219 V
version 7.0, 24 VERIFY_ALL_COLUMNS
upgrades replication option, 546
COMPRESSION option, 465 VERIFY_ALL_COLUMNS option, 351
SQL Remote, 465 VERIFY_THRESHOLD
upgrading replication option, 545
about, 239 Verify_threshold option
replication, 487 message size, 307
SQL Remote, 487 version 6.0.2
SQL Remote installations, 415 new features, 220
upgrading applications version 6.0.3
using multiple MobiLink script versions, 67 behavior changes, 25, 219
upload stream new features, 25, 218
defined, 32 upgrade issues, 26, 219
event, 78 version 7.0
processing of MobiLink, 45 behavior changes, 24, 217
upload_cursor event new features, 23, 217
occurrence, 78 upgrade issues, 24
upload_cursor script versions
about, 64, 77 of MobiLink synchronization scripts, 67
example, 98 VIM
upload_cursor table script control parameters, 453
MobiLink syntax, 188 message system, 452
uploading rows, 77 VIM message type, 441
user control parameter about, 578
FTP message system, 447 VIM messages
user IDs about, 581, 588
extracting groups, 423
Message Agent, 499

705
W–X

Windows NT
W availability on, 677
WHERE clause
supported message systems, 441
in publications, 321, 373
Windows services
whole table
running MobiLink synchronization servers as, 41
publishing, 317
worker threads
Windows 3.x
Message Agent, 458
supported message systems, 441
writing
Windows 95
MobiLink synchronization scripts, 57
supported message systems, 441
Windows 95/98
availability on, 677
Windows CE X
ActiveSync, 677 X509 certificates
replication, 677 generating new elliptic-curve, 164
reading elliptic-curve, 164

706

You might also like