msi: Make MsiDatabaseOpenView() RPC-compatible.
[wine.git] / dlls / msi / database.c
blobc1cf493dde6d8ab98588468ff663b2a9d69a9947
1 /*
2 * Implementation of the Microsoft Installer (msi.dll)
4 * Copyright 2002,2003,2004,2005 Mike McCormack for CodeWeavers
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21 #include <stdarg.h>
22 #include <stdio.h>
24 #define COBJMACROS
26 #include "windef.h"
27 #include "winbase.h"
28 #include "winreg.h"
29 #include "winnls.h"
30 #include "wine/debug.h"
31 #include "wine/unicode.h"
32 #include "msi.h"
33 #include "msiquery.h"
34 #include "msipriv.h"
35 #include "objidl.h"
36 #include "objbase.h"
37 #include "msiserver.h"
38 #include "query.h"
40 #include "initguid.h"
42 WINE_DEFAULT_DEBUG_CHANNEL(msi);
45 * .MSI file format
47 * An .msi file is a structured storage file.
48 * It contains a number of streams.
49 * A stream for each table in the database.
50 * Two streams for the string table in the database.
51 * Any binary data in a table is a reference to a stream.
54 #define IS_INTMSIDBOPEN(x) (((ULONG_PTR)(x) >> 16) == 0)
56 static void free_transforms( MSIDATABASE *db )
58 while( !list_empty( &db->transforms ) )
60 MSITRANSFORM *t = LIST_ENTRY( list_head( &db->transforms ), MSITRANSFORM, entry );
61 list_remove( &t->entry );
62 IStorage_Release( t->stg );
63 msi_free( t );
67 static void free_streams( MSIDATABASE *db )
69 UINT i;
70 for (i = 0; i < db->num_streams; i++)
72 if (db->streams[i].stream) IStream_Release( db->streams[i].stream );
74 msi_free( db->streams );
77 void append_storage_to_db( MSIDATABASE *db, IStorage *stg )
79 MSITRANSFORM *t;
81 t = msi_alloc( sizeof *t );
82 t->stg = stg;
83 IStorage_AddRef( stg );
84 list_add_head( &db->transforms, &t->entry );
87 static VOID MSI_CloseDatabase( MSIOBJECTHDR *arg )
89 MSIDATABASE *db = (MSIDATABASE *) arg;
91 msi_free(db->path);
92 free_streams( db );
93 free_cached_tables( db );
94 free_transforms( db );
95 if (db->strings) msi_destroy_stringtable( db->strings );
96 IStorage_Release( db->storage );
97 if (db->deletefile)
99 DeleteFileW( db->deletefile );
100 msi_free( db->deletefile );
102 msi_free( db->tempfolder );
105 static HRESULT db_initialize( IStorage *stg, const GUID *clsid )
107 static const WCHAR szTables[] = { '_','T','a','b','l','e','s',0 };
108 HRESULT hr;
110 hr = IStorage_SetClass( stg, clsid );
111 if (FAILED( hr ))
113 WARN("failed to set class id 0x%08x\n", hr);
114 return hr;
117 /* create the _Tables stream */
118 hr = write_stream_data( stg, szTables, NULL, 0, TRUE );
119 if (FAILED( hr ))
121 WARN("failed to create _Tables stream 0x%08x\n", hr);
122 return hr;
125 hr = msi_init_string_table( stg );
126 if (FAILED( hr ))
128 WARN("failed to initialize string table 0x%08x\n", hr);
129 return hr;
132 hr = IStorage_Commit( stg, 0 );
133 if (FAILED( hr ))
135 WARN("failed to commit changes 0x%08x\n", hr);
136 return hr;
139 return S_OK;
142 UINT MSI_OpenDatabaseW(LPCWSTR szDBPath, LPCWSTR szPersist, MSIDATABASE **pdb)
144 IStorage *stg = NULL;
145 HRESULT r;
146 MSIDATABASE *db = NULL;
147 UINT ret = ERROR_FUNCTION_FAILED;
148 LPCWSTR szMode, save_path;
149 STATSTG stat;
150 BOOL created = FALSE, patch = FALSE;
151 WCHAR path[MAX_PATH];
153 TRACE("%s %s\n",debugstr_w(szDBPath),debugstr_w(szPersist) );
155 if( !pdb )
156 return ERROR_INVALID_PARAMETER;
158 if (szPersist - MSIDBOPEN_PATCHFILE <= MSIDBOPEN_CREATEDIRECT)
160 TRACE("Database is a patch\n");
161 szPersist -= MSIDBOPEN_PATCHFILE;
162 patch = TRUE;
165 save_path = szDBPath;
166 szMode = szPersist;
167 if( !IS_INTMSIDBOPEN(szPersist) )
169 if (!CopyFileW( szDBPath, szPersist, FALSE ))
170 return ERROR_OPEN_FAILED;
172 szDBPath = szPersist;
173 szPersist = MSIDBOPEN_TRANSACT;
174 created = TRUE;
177 if( szPersist == MSIDBOPEN_READONLY )
179 r = StgOpenStorage( szDBPath, NULL,
180 STGM_DIRECT|STGM_READ|STGM_SHARE_DENY_WRITE, NULL, 0, &stg);
182 else if( szPersist == MSIDBOPEN_CREATE )
184 r = StgCreateDocfile( szDBPath,
185 STGM_CREATE|STGM_TRANSACTED|STGM_READWRITE|STGM_SHARE_EXCLUSIVE, 0, &stg );
187 if( SUCCEEDED(r) )
188 r = db_initialize( stg, patch ? &CLSID_MsiPatch : &CLSID_MsiDatabase );
189 created = TRUE;
191 else if( szPersist == MSIDBOPEN_CREATEDIRECT )
193 r = StgCreateDocfile( szDBPath,
194 STGM_CREATE|STGM_DIRECT|STGM_READWRITE|STGM_SHARE_EXCLUSIVE, 0, &stg );
196 if( SUCCEEDED(r) )
197 r = db_initialize( stg, patch ? &CLSID_MsiPatch : &CLSID_MsiDatabase );
198 created = TRUE;
200 else if( szPersist == MSIDBOPEN_TRANSACT )
202 r = StgOpenStorage( szDBPath, NULL,
203 STGM_TRANSACTED|STGM_READWRITE|STGM_SHARE_DENY_WRITE, NULL, 0, &stg);
205 else if( szPersist == MSIDBOPEN_DIRECT )
207 r = StgOpenStorage( szDBPath, NULL,
208 STGM_DIRECT|STGM_READWRITE|STGM_SHARE_EXCLUSIVE, NULL, 0, &stg);
210 else
212 ERR("unknown flag %p\n",szPersist);
213 return ERROR_INVALID_PARAMETER;
216 if( FAILED( r ) || !stg )
218 WARN("open failed r = %08x for %s\n", r, debugstr_w(szDBPath));
219 return ERROR_FUNCTION_FAILED;
222 r = IStorage_Stat( stg, &stat, STATFLAG_NONAME );
223 if( FAILED( r ) )
225 FIXME("Failed to stat storage\n");
226 goto end;
229 if ( !IsEqualGUID( &stat.clsid, &CLSID_MsiDatabase ) &&
230 !IsEqualGUID( &stat.clsid, &CLSID_MsiPatch ) &&
231 !IsEqualGUID( &stat.clsid, &CLSID_MsiTransform ) )
233 ERR("storage GUID is not a MSI database GUID %s\n",
234 debugstr_guid(&stat.clsid) );
235 goto end;
238 if ( patch && !IsEqualGUID( &stat.clsid, &CLSID_MsiPatch ) )
240 ERR("storage GUID is not the MSI patch GUID %s\n",
241 debugstr_guid(&stat.clsid) );
242 ret = ERROR_OPEN_FAILED;
243 goto end;
246 db = alloc_msiobject( MSIHANDLETYPE_DATABASE, sizeof (MSIDATABASE),
247 MSI_CloseDatabase );
248 if( !db )
250 FIXME("Failed to allocate a handle\n");
251 goto end;
254 if (!strchrW( save_path, '\\' ))
256 GetCurrentDirectoryW( MAX_PATH, path );
257 lstrcatW( path, szBackSlash );
258 lstrcatW( path, save_path );
260 else
261 lstrcpyW( path, save_path );
263 db->path = strdupW( path );
264 db->media_transform_offset = MSI_INITIAL_MEDIA_TRANSFORM_OFFSET;
265 db->media_transform_disk_id = MSI_INITIAL_MEDIA_TRANSFORM_DISKID;
267 if( TRACE_ON( msi ) )
268 enum_stream_names( stg );
270 db->storage = stg;
271 db->mode = szMode;
272 if (created)
273 db->deletefile = strdupW( szDBPath );
274 list_init( &db->tables );
275 list_init( &db->transforms );
277 db->strings = msi_load_string_table( stg, &db->bytes_per_strref );
278 if( !db->strings )
279 goto end;
281 ret = ERROR_SUCCESS;
283 msiobj_addref( &db->hdr );
284 IStorage_AddRef( stg );
285 *pdb = db;
287 end:
288 if( db )
289 msiobj_release( &db->hdr );
290 if( stg )
291 IStorage_Release( stg );
293 return ret;
296 UINT WINAPI MsiOpenDatabaseW(LPCWSTR szDBPath, LPCWSTR szPersist, MSIHANDLE *phDB)
298 MSIDATABASE *db;
299 UINT ret;
301 TRACE("%s %s %p\n",debugstr_w(szDBPath),debugstr_w(szPersist), phDB);
303 ret = MSI_OpenDatabaseW( szDBPath, szPersist, &db );
304 if( ret == ERROR_SUCCESS )
306 *phDB = alloc_msihandle( &db->hdr );
307 if (! *phDB)
308 ret = ERROR_NOT_ENOUGH_MEMORY;
309 msiobj_release( &db->hdr );
312 return ret;
315 UINT WINAPI MsiOpenDatabaseA(LPCSTR szDBPath, LPCSTR szPersist, MSIHANDLE *phDB)
317 HRESULT r = ERROR_FUNCTION_FAILED;
318 LPWSTR szwDBPath = NULL, szwPersist = NULL;
320 TRACE("%s %s %p\n", debugstr_a(szDBPath), debugstr_a(szPersist), phDB);
322 if( szDBPath )
324 szwDBPath = strdupAtoW( szDBPath );
325 if( !szwDBPath )
326 goto end;
329 if( !IS_INTMSIDBOPEN(szPersist) )
331 szwPersist = strdupAtoW( szPersist );
332 if( !szwPersist )
333 goto end;
335 else
336 szwPersist = (LPWSTR)(DWORD_PTR)szPersist;
338 r = MsiOpenDatabaseW( szwDBPath, szwPersist, phDB );
340 end:
341 if( !IS_INTMSIDBOPEN(szPersist) )
342 msi_free( szwPersist );
343 msi_free( szwDBPath );
345 return r;
348 static LPWSTR msi_read_text_archive(LPCWSTR path, DWORD *len)
350 HANDLE file;
351 LPSTR data = NULL;
352 LPWSTR wdata = NULL;
353 DWORD read, size = 0;
355 file = CreateFileW( path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL );
356 if (file == INVALID_HANDLE_VALUE)
357 return NULL;
359 size = GetFileSize( file, NULL );
360 if (!(data = msi_alloc( size ))) goto done;
362 if (!ReadFile( file, data, size, &read, NULL ) || read != size) goto done;
364 while (!data[size - 1]) size--;
365 *len = MultiByteToWideChar( CP_ACP, 0, data, size, NULL, 0 );
366 if ((wdata = msi_alloc( (*len + 1) * sizeof(WCHAR) )))
368 MultiByteToWideChar( CP_ACP, 0, data, size, wdata, *len );
369 wdata[*len] = 0;
372 done:
373 CloseHandle( file );
374 msi_free( data );
375 return wdata;
378 static void msi_parse_line(LPWSTR *line, LPWSTR **entries, DWORD *num_entries, DWORD *len)
380 LPWSTR ptr = *line, save;
381 DWORD i, count = 1, chars_left = *len;
383 *entries = NULL;
385 /* stay on this line */
386 while (chars_left && *ptr != '\n')
388 /* entries are separated by tabs */
389 if (*ptr == '\t')
390 count++;
392 ptr++;
393 chars_left--;
396 *entries = msi_alloc(count * sizeof(LPWSTR));
397 if (!*entries)
398 return;
400 /* store pointers into the data */
401 chars_left = *len;
402 for (i = 0, ptr = *line; i < count; i++)
404 while (chars_left && *ptr == '\r')
406 ptr++;
407 chars_left--;
409 save = ptr;
411 while (chars_left && *ptr != '\t' && *ptr != '\n' && *ptr != '\r')
413 if (!*ptr) *ptr = '\n'; /* convert embedded nulls to \n */
414 if (ptr > *line && *ptr == '\x19' && *(ptr - 1) == '\x11')
416 *ptr = '\n';
417 *(ptr - 1) = '\r';
419 ptr++;
420 chars_left--;
423 /* NULL-separate the data */
424 if (*ptr == '\n' || *ptr == '\r')
426 while (chars_left && (*ptr == '\n' || *ptr == '\r'))
428 *(ptr++) = 0;
429 chars_left--;
432 else if (*ptr)
434 *(ptr++) = 0;
435 chars_left--;
437 (*entries)[i] = save;
440 /* move to the next line if there's more, else EOF */
441 *line = ptr;
442 *len = chars_left;
443 if (num_entries)
444 *num_entries = count;
447 static LPWSTR msi_build_createsql_prelude(LPWSTR table)
449 LPWSTR prelude;
450 DWORD size;
452 static const WCHAR create_fmt[] = {'C','R','E','A','T','E',' ','T','A','B','L','E',' ','`','%','s','`',' ','(',' ',0};
454 size = sizeof(create_fmt)/sizeof(create_fmt[0]) + lstrlenW(table) - 2;
455 prelude = msi_alloc(size * sizeof(WCHAR));
456 if (!prelude)
457 return NULL;
459 sprintfW(prelude, create_fmt, table);
460 return prelude;
463 static LPWSTR msi_build_createsql_columns(LPWSTR *columns_data, LPWSTR *types, DWORD num_columns)
465 LPWSTR columns, p;
466 LPCWSTR type;
467 DWORD sql_size = 1, i, len;
468 WCHAR expanded[128], *ptr;
469 WCHAR size[10], comma[2], extra[30];
471 static const WCHAR column_fmt[] = {'`','%','s','`',' ','%','s','%','s','%','s','%','s',' ',0};
472 static const WCHAR size_fmt[] = {'(','%','s',')',0};
473 static const WCHAR type_char[] = {'C','H','A','R',0};
474 static const WCHAR type_int[] = {'I','N','T',0};
475 static const WCHAR type_long[] = {'L','O','N','G',0};
476 static const WCHAR type_object[] = {'O','B','J','E','C','T',0};
477 static const WCHAR type_notnull[] = {' ','N','O','T',' ','N','U','L','L',0};
478 static const WCHAR localizable[] = {' ','L','O','C','A','L','I','Z','A','B','L','E',0};
480 columns = msi_alloc_zero(sql_size * sizeof(WCHAR));
481 if (!columns)
482 return NULL;
484 for (i = 0; i < num_columns; i++)
486 type = NULL;
487 comma[1] = size[0] = extra[0] = '\0';
489 if (i == num_columns - 1)
490 comma[0] = '\0';
491 else
492 comma[0] = ',';
494 ptr = &types[i][1];
495 len = atolW(ptr);
496 extra[0] = '\0';
498 switch (types[i][0])
500 case 'l':
501 lstrcpyW(extra, type_notnull);
502 /* fall through */
503 case 'L':
504 lstrcatW(extra, localizable);
505 type = type_char;
506 sprintfW(size, size_fmt, ptr);
507 break;
508 case 's':
509 lstrcpyW(extra, type_notnull);
510 /* fall through */
511 case 'S':
512 type = type_char;
513 sprintfW(size, size_fmt, ptr);
514 break;
515 case 'i':
516 lstrcpyW(extra, type_notnull);
517 /* fall through */
518 case 'I':
519 if (len <= 2)
520 type = type_int;
521 else if (len == 4)
522 type = type_long;
523 else
525 WARN("invalid int width %u\n", len);
526 msi_free(columns);
527 return NULL;
529 break;
530 case 'v':
531 lstrcpyW(extra, type_notnull);
532 /* fall through */
533 case 'V':
534 type = type_object;
535 break;
536 default:
537 ERR("Unknown type: %c\n", types[i][0]);
538 msi_free(columns);
539 return NULL;
542 sprintfW(expanded, column_fmt, columns_data[i], type, size, extra, comma);
543 sql_size += lstrlenW(expanded);
545 p = msi_realloc(columns, sql_size * sizeof(WCHAR));
546 if (!p)
548 msi_free(columns);
549 return NULL;
551 columns = p;
553 lstrcatW(columns, expanded);
556 return columns;
559 static LPWSTR msi_build_createsql_postlude(LPWSTR *primary_keys, DWORD num_keys)
561 LPWSTR postlude, keys, ptr;
562 DWORD size, i;
564 static const WCHAR key_fmt[] = {'`','%','s','`',',',' ',0};
565 static const WCHAR postlude_fmt[] = {'P','R','I','M','A','R','Y',' ','K','E','Y',' ','%','s',')',0};
567 for (i = 0, size = 1; i < num_keys; i++)
568 size += lstrlenW(key_fmt) + lstrlenW(primary_keys[i]) - 2;
570 keys = msi_alloc(size * sizeof(WCHAR));
571 if (!keys)
572 return NULL;
574 for (i = 0, ptr = keys; i < num_keys; i++)
576 ptr += sprintfW(ptr, key_fmt, primary_keys[i]);
579 /* remove final ', ' */
580 *(ptr - 2) = '\0';
582 size = lstrlenW(postlude_fmt) + size - 1;
583 postlude = msi_alloc(size * sizeof(WCHAR));
584 if (!postlude)
585 goto done;
587 sprintfW(postlude, postlude_fmt, keys);
589 done:
590 msi_free(keys);
591 return postlude;
594 static UINT msi_add_table_to_db(MSIDATABASE *db, LPWSTR *columns, LPWSTR *types, LPWSTR *labels, DWORD num_labels, DWORD num_columns)
596 UINT r = ERROR_OUTOFMEMORY;
597 DWORD size;
598 MSIQUERY *view;
599 LPWSTR create_sql = NULL;
600 LPWSTR prelude, columns_sql, postlude;
602 prelude = msi_build_createsql_prelude(labels[0]);
603 columns_sql = msi_build_createsql_columns(columns, types, num_columns);
604 postlude = msi_build_createsql_postlude(labels + 1, num_labels - 1); /* skip over table name */
606 if (!prelude || !columns_sql || !postlude)
607 goto done;
609 size = lstrlenW(prelude) + lstrlenW(columns_sql) + lstrlenW(postlude) + 1;
610 create_sql = msi_alloc(size * sizeof(WCHAR));
611 if (!create_sql)
612 goto done;
614 lstrcpyW(create_sql, prelude);
615 lstrcatW(create_sql, columns_sql);
616 lstrcatW(create_sql, postlude);
618 r = MSI_DatabaseOpenViewW( db, create_sql, &view );
619 if (r != ERROR_SUCCESS)
620 goto done;
622 r = MSI_ViewExecute(view, NULL);
623 MSI_ViewClose(view);
624 msiobj_release(&view->hdr);
626 done:
627 msi_free(prelude);
628 msi_free(columns_sql);
629 msi_free(postlude);
630 msi_free(create_sql);
631 return r;
634 static LPWSTR msi_import_stream_filename(LPCWSTR path, LPCWSTR name)
636 DWORD len;
637 LPWSTR fullname, ptr;
639 len = lstrlenW(path) + lstrlenW(name) + 1;
640 fullname = msi_alloc(len*sizeof(WCHAR));
641 if (!fullname)
642 return NULL;
644 lstrcpyW( fullname, path );
646 /* chop off extension from path */
647 ptr = strrchrW(fullname, '.');
648 if (!ptr)
650 msi_free (fullname);
651 return NULL;
653 *ptr++ = '\\';
654 lstrcpyW( ptr, name );
655 return fullname;
658 static UINT construct_record(DWORD num_columns, LPWSTR *types,
659 LPWSTR *data, LPWSTR path, MSIRECORD **rec)
661 UINT i;
663 *rec = MSI_CreateRecord(num_columns);
664 if (!*rec)
665 return ERROR_OUTOFMEMORY;
667 for (i = 0; i < num_columns; i++)
669 switch (types[i][0])
671 case 'L': case 'l': case 'S': case 's':
672 MSI_RecordSetStringW(*rec, i + 1, data[i]);
673 break;
674 case 'I': case 'i':
675 if (*data[i])
676 MSI_RecordSetInteger(*rec, i + 1, atoiW(data[i]));
677 break;
678 case 'V': case 'v':
679 if (*data[i])
681 UINT r;
682 LPWSTR file = msi_import_stream_filename(path, data[i]);
683 if (!file)
684 return ERROR_FUNCTION_FAILED;
686 r = MSI_RecordSetStreamFromFileW(*rec, i + 1, file);
687 msi_free (file);
688 if (r != ERROR_SUCCESS)
689 return ERROR_FUNCTION_FAILED;
691 break;
692 default:
693 ERR("Unhandled column type: %c\n", types[i][0]);
694 msiobj_release(&(*rec)->hdr);
695 return ERROR_FUNCTION_FAILED;
699 return ERROR_SUCCESS;
702 static UINT msi_add_records_to_table(MSIDATABASE *db, LPWSTR *columns, LPWSTR *types,
703 LPWSTR *labels, LPWSTR **records,
704 int num_columns, int num_records,
705 LPWSTR path)
707 UINT r;
708 int i;
709 MSIQUERY *view;
710 MSIRECORD *rec;
712 static const WCHAR select[] = {
713 'S','E','L','E','C','T',' ','*',' ',
714 'F','R','O','M',' ','`','%','s','`',0
717 r = MSI_OpenQuery(db, &view, select, labels[0]);
718 if (r != ERROR_SUCCESS)
719 return r;
721 while (MSI_ViewFetch(view, &rec) != ERROR_NO_MORE_ITEMS)
723 r = MSI_ViewModify(view, MSIMODIFY_DELETE, rec);
724 msiobj_release(&rec->hdr);
725 if (r != ERROR_SUCCESS)
726 goto done;
729 for (i = 0; i < num_records; i++)
731 r = construct_record(num_columns, types, records[i], path, &rec);
732 if (r != ERROR_SUCCESS)
733 goto done;
735 r = MSI_ViewModify(view, MSIMODIFY_INSERT, rec);
736 if (r != ERROR_SUCCESS)
738 msiobj_release(&rec->hdr);
739 goto done;
742 msiobj_release(&rec->hdr);
745 done:
746 msiobj_release(&view->hdr);
747 return r;
750 static UINT MSI_DatabaseImport(MSIDATABASE *db, LPCWSTR folder, LPCWSTR file)
752 UINT r;
753 DWORD len, i;
754 DWORD num_labels, num_types;
755 DWORD num_columns, num_records = 0;
756 LPWSTR *columns, *types, *labels;
757 LPWSTR path, ptr, data;
758 LPWSTR **records = NULL;
759 LPWSTR **temp_records;
761 static const WCHAR suminfo[] =
762 {'_','S','u','m','m','a','r','y','I','n','f','o','r','m','a','t','i','o','n',0};
763 static const WCHAR forcecodepage[] =
764 {'_','F','o','r','c','e','C','o','d','e','p','a','g','e',0};
766 TRACE("%p %s %s\n", db, debugstr_w(folder), debugstr_w(file) );
768 if( folder == NULL || file == NULL )
769 return ERROR_INVALID_PARAMETER;
771 len = lstrlenW(folder) + lstrlenW(szBackSlash) + lstrlenW(file) + 1;
772 path = msi_alloc( len * sizeof(WCHAR) );
773 if (!path)
774 return ERROR_OUTOFMEMORY;
776 lstrcpyW( path, folder );
777 lstrcatW( path, szBackSlash );
778 lstrcatW( path, file );
780 data = msi_read_text_archive( path, &len );
781 if (!data)
783 msi_free(path);
784 return ERROR_FUNCTION_FAILED;
787 ptr = data;
788 msi_parse_line( &ptr, &columns, &num_columns, &len );
789 msi_parse_line( &ptr, &types, &num_types, &len );
790 msi_parse_line( &ptr, &labels, &num_labels, &len );
792 if (num_columns == 1 && !columns[0][0] && num_labels == 1 && !labels[0][0] &&
793 num_types == 2 && !strcmpW( types[1], forcecodepage ))
795 r = msi_set_string_table_codepage( db->strings, atoiW( types[0] ) );
796 goto done;
799 if (num_columns != num_types)
801 r = ERROR_FUNCTION_FAILED;
802 goto done;
805 records = msi_alloc(sizeof(LPWSTR *));
806 if (!records)
808 r = ERROR_OUTOFMEMORY;
809 goto done;
812 /* read in the table records */
813 while (len)
815 msi_parse_line( &ptr, &records[num_records], NULL, &len );
817 num_records++;
818 temp_records = msi_realloc(records, (num_records + 1) * sizeof(LPWSTR *));
819 if (!temp_records)
821 r = ERROR_OUTOFMEMORY;
822 goto done;
824 records = temp_records;
827 if (!strcmpW(labels[0], suminfo))
829 r = msi_add_suminfo( db, records, num_records, num_columns );
830 if (r != ERROR_SUCCESS)
832 r = ERROR_FUNCTION_FAILED;
833 goto done;
836 else
838 if (!TABLE_Exists(db, labels[0]))
840 r = msi_add_table_to_db( db, columns, types, labels, num_labels, num_columns );
841 if (r != ERROR_SUCCESS)
843 r = ERROR_FUNCTION_FAILED;
844 goto done;
848 r = msi_add_records_to_table( db, columns, types, labels, records, num_columns, num_records, path );
851 done:
852 msi_free(path);
853 msi_free(data);
854 msi_free(columns);
855 msi_free(types);
856 msi_free(labels);
858 for (i = 0; i < num_records; i++)
859 msi_free(records[i]);
861 msi_free(records);
863 return r;
866 UINT WINAPI MsiDatabaseImportW(MSIHANDLE handle, LPCWSTR szFolder, LPCWSTR szFilename)
868 MSIDATABASE *db;
869 UINT r;
871 TRACE("%x %s %s\n",handle,debugstr_w(szFolder), debugstr_w(szFilename));
873 db = msihandle2msiinfo( handle, MSIHANDLETYPE_DATABASE );
874 if( !db )
876 MSIHANDLE remote_database = msi_get_remote( handle );
877 if ( !remote_database )
878 return ERROR_INVALID_HANDLE;
880 WARN("MsiDatabaseImport not allowed during a custom action!\n");
882 return ERROR_SUCCESS;
885 r = MSI_DatabaseImport( db, szFolder, szFilename );
886 msiobj_release( &db->hdr );
887 return r;
890 UINT WINAPI MsiDatabaseImportA( MSIHANDLE handle,
891 LPCSTR szFolder, LPCSTR szFilename )
893 LPWSTR path = NULL, file = NULL;
894 UINT r = ERROR_OUTOFMEMORY;
896 TRACE("%x %s %s\n", handle, debugstr_a(szFolder), debugstr_a(szFilename));
898 if( szFolder )
900 path = strdupAtoW( szFolder );
901 if( !path )
902 goto end;
905 if( szFilename )
907 file = strdupAtoW( szFilename );
908 if( !file )
909 goto end;
912 r = MsiDatabaseImportW( handle, path, file );
914 end:
915 msi_free( path );
916 msi_free( file );
918 return r;
921 static UINT msi_export_record( HANDLE handle, MSIRECORD *row, UINT start )
923 UINT i, count, len, r = ERROR_SUCCESS;
924 const char *sep;
925 char *buffer;
926 DWORD sz;
928 len = 0x100;
929 buffer = msi_alloc( len );
930 if ( !buffer )
931 return ERROR_OUTOFMEMORY;
933 count = MSI_RecordGetFieldCount( row );
934 for ( i=start; i<=count; i++ )
936 sz = len;
937 r = MSI_RecordGetStringA( row, i, buffer, &sz );
938 if (r == ERROR_MORE_DATA)
940 char *p = msi_realloc( buffer, sz + 1 );
941 if (!p)
942 break;
943 len = sz + 1;
944 buffer = p;
946 sz = len;
947 r = MSI_RecordGetStringA( row, i, buffer, &sz );
948 if (r != ERROR_SUCCESS)
949 break;
951 if (!WriteFile( handle, buffer, sz, &sz, NULL ))
953 r = ERROR_FUNCTION_FAILED;
954 break;
957 sep = (i < count) ? "\t" : "\r\n";
958 if (!WriteFile( handle, sep, strlen(sep), &sz, NULL ))
960 r = ERROR_FUNCTION_FAILED;
961 break;
964 msi_free( buffer );
965 return r;
968 static UINT msi_export_row( MSIRECORD *row, void *arg )
970 return msi_export_record( arg, row, 1 );
973 static UINT msi_export_forcecodepage( HANDLE handle, UINT codepage )
975 static const char fmt[] = "\r\n\r\n%u\t_ForceCodepage\r\n";
976 char data[sizeof(fmt) + 10];
977 DWORD sz;
979 sprintf( data, fmt, codepage );
981 sz = lstrlenA(data) + 1;
982 if (!WriteFile(handle, data, sz, &sz, NULL))
983 return ERROR_FUNCTION_FAILED;
985 return ERROR_SUCCESS;
988 static UINT MSI_DatabaseExport( MSIDATABASE *db, LPCWSTR table,
989 LPCWSTR folder, LPCWSTR file )
991 static const WCHAR query[] = {
992 's','e','l','e','c','t',' ','*',' ','f','r','o','m',' ','%','s',0 };
993 static const WCHAR forcecodepage[] = {
994 '_','F','o','r','c','e','C','o','d','e','p','a','g','e',0 };
995 MSIRECORD *rec = NULL;
996 MSIQUERY *view = NULL;
997 LPWSTR filename;
998 HANDLE handle;
999 UINT len, r;
1001 TRACE("%p %s %s %s\n", db, debugstr_w(table),
1002 debugstr_w(folder), debugstr_w(file) );
1004 if( folder == NULL || file == NULL )
1005 return ERROR_INVALID_PARAMETER;
1007 len = lstrlenW(folder) + lstrlenW(file) + 2;
1008 filename = msi_alloc(len * sizeof (WCHAR));
1009 if (!filename)
1010 return ERROR_OUTOFMEMORY;
1012 lstrcpyW( filename, folder );
1013 lstrcatW( filename, szBackSlash );
1014 lstrcatW( filename, file );
1016 handle = CreateFileW( filename, GENERIC_READ | GENERIC_WRITE, 0,
1017 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
1018 msi_free( filename );
1019 if (handle == INVALID_HANDLE_VALUE)
1020 return ERROR_FUNCTION_FAILED;
1022 if (!strcmpW( table, forcecodepage ))
1024 UINT codepage = msi_get_string_table_codepage( db->strings );
1025 r = msi_export_forcecodepage( handle, codepage );
1026 goto done;
1029 r = MSI_OpenQuery( db, &view, query, table );
1030 if (r == ERROR_SUCCESS)
1032 /* write out row 1, the column names */
1033 r = MSI_ViewGetColumnInfo(view, MSICOLINFO_NAMES, &rec);
1034 if (r == ERROR_SUCCESS)
1036 msi_export_record( handle, rec, 1 );
1037 msiobj_release( &rec->hdr );
1040 /* write out row 2, the column types */
1041 r = MSI_ViewGetColumnInfo(view, MSICOLINFO_TYPES, &rec);
1042 if (r == ERROR_SUCCESS)
1044 msi_export_record( handle, rec, 1 );
1045 msiobj_release( &rec->hdr );
1048 /* write out row 3, the table name + keys */
1049 r = MSI_DatabaseGetPrimaryKeys( db, table, &rec );
1050 if (r == ERROR_SUCCESS)
1052 MSI_RecordSetStringW( rec, 0, table );
1053 msi_export_record( handle, rec, 0 );
1054 msiobj_release( &rec->hdr );
1057 /* write out row 4 onwards, the data */
1058 r = MSI_IterateRecords( view, 0, msi_export_row, handle );
1059 msiobj_release( &view->hdr );
1062 done:
1063 CloseHandle( handle );
1064 return r;
1067 /***********************************************************************
1068 * MsiExportDatabaseW [MSI.@]
1070 * Writes a file containing the table data as tab separated ASCII.
1072 * The format is as follows:
1074 * row1 : colname1 <tab> colname2 <tab> .... colnameN <cr> <lf>
1075 * row2 : coltype1 <tab> coltype2 <tab> .... coltypeN <cr> <lf>
1076 * row3 : tablename <tab> key1 <tab> key2 <tab> ... keyM <cr> <lf>
1078 * Followed by the data, starting at row 1 with one row per line
1080 * row4 : data <tab> data <tab> data <tab> ... data <cr> <lf>
1082 UINT WINAPI MsiDatabaseExportW( MSIHANDLE handle, LPCWSTR szTable,
1083 LPCWSTR szFolder, LPCWSTR szFilename )
1085 MSIDATABASE *db;
1086 UINT r;
1088 TRACE("%x %s %s %s\n", handle, debugstr_w(szTable),
1089 debugstr_w(szFolder), debugstr_w(szFilename));
1091 db = msihandle2msiinfo( handle, MSIHANDLETYPE_DATABASE );
1092 if( !db )
1094 MSIHANDLE remote_database = msi_get_remote(handle);
1095 if ( !remote_database )
1096 return ERROR_INVALID_HANDLE;
1098 WARN("MsiDatabaseExport not allowed during a custom action!\n");
1100 return ERROR_SUCCESS;
1103 r = MSI_DatabaseExport( db, szTable, szFolder, szFilename );
1104 msiobj_release( &db->hdr );
1105 return r;
1108 UINT WINAPI MsiDatabaseExportA( MSIHANDLE handle, LPCSTR szTable,
1109 LPCSTR szFolder, LPCSTR szFilename )
1111 LPWSTR path = NULL, file = NULL, table = NULL;
1112 UINT r = ERROR_OUTOFMEMORY;
1114 TRACE("%x %s %s %s\n", handle, debugstr_a(szTable),
1115 debugstr_a(szFolder), debugstr_a(szFilename));
1117 if( szTable )
1119 table = strdupAtoW( szTable );
1120 if( !table )
1121 goto end;
1124 if( szFolder )
1126 path = strdupAtoW( szFolder );
1127 if( !path )
1128 goto end;
1131 if( szFilename )
1133 file = strdupAtoW( szFilename );
1134 if( !file )
1135 goto end;
1138 r = MsiDatabaseExportW( handle, table, path, file );
1140 end:
1141 msi_free( table );
1142 msi_free( path );
1143 msi_free( file );
1145 return r;
1148 UINT WINAPI MsiDatabaseMergeA(MSIHANDLE hDatabase, MSIHANDLE hDatabaseMerge,
1149 LPCSTR szTableName)
1151 UINT r;
1152 LPWSTR table;
1154 TRACE("(%d, %d, %s)\n", hDatabase, hDatabaseMerge,
1155 debugstr_a(szTableName));
1157 table = strdupAtoW(szTableName);
1158 r = MsiDatabaseMergeW(hDatabase, hDatabaseMerge, table);
1160 msi_free(table);
1161 return r;
1164 typedef struct _tagMERGETABLE
1166 struct list entry;
1167 struct list rows;
1168 LPWSTR name;
1169 DWORD numconflicts;
1170 LPWSTR *columns;
1171 DWORD numcolumns;
1172 LPWSTR *types;
1173 DWORD numtypes;
1174 LPWSTR *labels;
1175 DWORD numlabels;
1176 } MERGETABLE;
1178 typedef struct _tagMERGEROW
1180 struct list entry;
1181 MSIRECORD *data;
1182 } MERGEROW;
1184 typedef struct _tagMERGEDATA
1186 MSIDATABASE *db;
1187 MSIDATABASE *merge;
1188 MERGETABLE *curtable;
1189 MSIQUERY *curview;
1190 struct list *tabledata;
1191 } MERGEDATA;
1193 static BOOL merge_type_match(LPCWSTR type1, LPCWSTR type2)
1195 if (((type1[0] == 'l') || (type1[0] == 's')) &&
1196 ((type2[0] == 'l') || (type2[0] == 's')))
1197 return TRUE;
1199 if (((type1[0] == 'L') || (type1[0] == 'S')) &&
1200 ((type2[0] == 'L') || (type2[0] == 'S')))
1201 return TRUE;
1203 return !strcmpW( type1, type2 );
1206 static UINT merge_verify_colnames(MSIQUERY *dbview, MSIQUERY *mergeview)
1208 MSIRECORD *dbrec, *mergerec;
1209 UINT r, i, count;
1211 r = MSI_ViewGetColumnInfo(dbview, MSICOLINFO_NAMES, &dbrec);
1212 if (r != ERROR_SUCCESS)
1213 return r;
1215 r = MSI_ViewGetColumnInfo(mergeview, MSICOLINFO_NAMES, &mergerec);
1216 if (r != ERROR_SUCCESS)
1218 msiobj_release(&dbrec->hdr);
1219 return r;
1222 count = MSI_RecordGetFieldCount(dbrec);
1223 for (i = 1; i <= count; i++)
1225 if (!MSI_RecordGetString(mergerec, i))
1226 break;
1228 if (strcmpW( MSI_RecordGetString( dbrec, i ), MSI_RecordGetString( mergerec, i ) ))
1230 r = ERROR_DATATYPE_MISMATCH;
1231 goto done;
1235 msiobj_release(&dbrec->hdr);
1236 msiobj_release(&mergerec->hdr);
1237 dbrec = mergerec = NULL;
1239 r = MSI_ViewGetColumnInfo(dbview, MSICOLINFO_TYPES, &dbrec);
1240 if (r != ERROR_SUCCESS)
1241 return r;
1243 r = MSI_ViewGetColumnInfo(mergeview, MSICOLINFO_TYPES, &mergerec);
1244 if (r != ERROR_SUCCESS)
1246 msiobj_release(&dbrec->hdr);
1247 return r;
1250 count = MSI_RecordGetFieldCount(dbrec);
1251 for (i = 1; i <= count; i++)
1253 if (!MSI_RecordGetString(mergerec, i))
1254 break;
1256 if (!merge_type_match(MSI_RecordGetString(dbrec, i),
1257 MSI_RecordGetString(mergerec, i)))
1259 r = ERROR_DATATYPE_MISMATCH;
1260 break;
1264 done:
1265 msiobj_release(&dbrec->hdr);
1266 msiobj_release(&mergerec->hdr);
1268 return r;
1271 static UINT merge_verify_primary_keys(MSIDATABASE *db, MSIDATABASE *mergedb,
1272 LPCWSTR table)
1274 MSIRECORD *dbrec, *mergerec = NULL;
1275 UINT r, i, count;
1277 r = MSI_DatabaseGetPrimaryKeys(db, table, &dbrec);
1278 if (r != ERROR_SUCCESS)
1279 return r;
1281 r = MSI_DatabaseGetPrimaryKeys(mergedb, table, &mergerec);
1282 if (r != ERROR_SUCCESS)
1283 goto done;
1285 count = MSI_RecordGetFieldCount(dbrec);
1286 if (count != MSI_RecordGetFieldCount(mergerec))
1288 r = ERROR_DATATYPE_MISMATCH;
1289 goto done;
1292 for (i = 1; i <= count; i++)
1294 if (strcmpW( MSI_RecordGetString( dbrec, i ), MSI_RecordGetString( mergerec, i ) ))
1296 r = ERROR_DATATYPE_MISMATCH;
1297 goto done;
1301 done:
1302 msiobj_release(&dbrec->hdr);
1303 msiobj_release(&mergerec->hdr);
1305 return r;
1308 static LPWSTR get_key_value(MSIQUERY *view, LPCWSTR key, MSIRECORD *rec)
1310 MSIRECORD *colnames;
1311 LPWSTR str, val;
1312 UINT r, i = 0, sz = 0;
1313 int cmp;
1315 r = MSI_ViewGetColumnInfo(view, MSICOLINFO_NAMES, &colnames);
1316 if (r != ERROR_SUCCESS)
1317 return NULL;
1321 str = msi_dup_record_field(colnames, ++i);
1322 cmp = strcmpW( key, str );
1323 msi_free(str);
1324 } while (cmp);
1326 msiobj_release(&colnames->hdr);
1328 r = MSI_RecordGetStringW(rec, i, NULL, &sz);
1329 if (r != ERROR_SUCCESS)
1330 return NULL;
1331 sz++;
1333 if (MSI_RecordGetString(rec, i)) /* check record field is a string */
1335 /* quote string record fields */
1336 const WCHAR szQuote[] = {'\'', 0};
1337 sz += 2;
1338 val = msi_alloc(sz*sizeof(WCHAR));
1339 if (!val)
1340 return NULL;
1342 lstrcpyW(val, szQuote);
1343 r = MSI_RecordGetStringW(rec, i, val+1, &sz);
1344 lstrcpyW(val+1+sz, szQuote);
1346 else
1348 /* do not quote integer record fields */
1349 val = msi_alloc(sz*sizeof(WCHAR));
1350 if (!val)
1351 return NULL;
1353 r = MSI_RecordGetStringW(rec, i, val, &sz);
1356 if (r != ERROR_SUCCESS)
1358 ERR("failed to get string!\n");
1359 msi_free(val);
1360 return NULL;
1363 return val;
1366 static LPWSTR create_diff_row_query(MSIDATABASE *merge, MSIQUERY *view,
1367 LPWSTR table, MSIRECORD *rec)
1369 LPWSTR query = NULL, clause = NULL, val;
1370 LPCWSTR setptr, key;
1371 DWORD size, oldsize;
1372 MSIRECORD *keys;
1373 UINT r, i, count;
1375 static const WCHAR keyset[] = {
1376 '`','%','s','`',' ','=',' ','%','s',' ','A','N','D',' ',0};
1377 static const WCHAR lastkeyset[] = {
1378 '`','%','s','`',' ','=',' ','%','s',' ',0};
1379 static const WCHAR fmt[] = {'S','E','L','E','C','T',' ','*',' ',
1380 'F','R','O','M',' ','`','%','s','`',' ',
1381 'W','H','E','R','E',' ','%','s',0};
1383 r = MSI_DatabaseGetPrimaryKeys(merge, table, &keys);
1384 if (r != ERROR_SUCCESS)
1385 return NULL;
1387 clause = msi_alloc_zero(sizeof(WCHAR));
1388 if (!clause)
1389 goto done;
1391 size = 1;
1392 count = MSI_RecordGetFieldCount(keys);
1393 for (i = 1; i <= count; i++)
1395 key = MSI_RecordGetString(keys, i);
1396 val = get_key_value(view, key, rec);
1398 if (i == count)
1399 setptr = lastkeyset;
1400 else
1401 setptr = keyset;
1403 oldsize = size;
1404 size += lstrlenW(setptr) + lstrlenW(key) + lstrlenW(val) - 4;
1405 clause = msi_realloc(clause, size * sizeof (WCHAR));
1406 if (!clause)
1408 msi_free(val);
1409 goto done;
1412 sprintfW(clause + oldsize - 1, setptr, key, val);
1413 msi_free(val);
1416 size = lstrlenW(fmt) + lstrlenW(table) + lstrlenW(clause) + 1;
1417 query = msi_alloc(size * sizeof(WCHAR));
1418 if (!query)
1419 goto done;
1421 sprintfW(query, fmt, table, clause);
1423 done:
1424 msi_free(clause);
1425 msiobj_release(&keys->hdr);
1426 return query;
1429 static UINT merge_diff_row(MSIRECORD *rec, LPVOID param)
1431 MERGEDATA *data = param;
1432 MERGETABLE *table = data->curtable;
1433 MERGEROW *mergerow;
1434 MSIQUERY *dbview = NULL;
1435 MSIRECORD *row = NULL;
1436 LPWSTR query = NULL;
1437 UINT r = ERROR_SUCCESS;
1439 if (TABLE_Exists(data->db, table->name))
1441 query = create_diff_row_query(data->merge, data->curview, table->name, rec);
1442 if (!query)
1443 return ERROR_OUTOFMEMORY;
1445 r = MSI_DatabaseOpenViewW(data->db, query, &dbview);
1446 if (r != ERROR_SUCCESS)
1447 goto done;
1449 r = MSI_ViewExecute(dbview, NULL);
1450 if (r != ERROR_SUCCESS)
1451 goto done;
1453 r = MSI_ViewFetch(dbview, &row);
1454 if (r == ERROR_SUCCESS && !MSI_RecordsAreEqual(rec, row))
1456 table->numconflicts++;
1457 goto done;
1459 else if (r != ERROR_NO_MORE_ITEMS)
1460 goto done;
1462 r = ERROR_SUCCESS;
1465 mergerow = msi_alloc(sizeof(MERGEROW));
1466 if (!mergerow)
1468 r = ERROR_OUTOFMEMORY;
1469 goto done;
1472 mergerow->data = MSI_CloneRecord(rec);
1473 if (!mergerow->data)
1475 r = ERROR_OUTOFMEMORY;
1476 msi_free(mergerow);
1477 goto done;
1480 list_add_tail(&table->rows, &mergerow->entry);
1482 done:
1483 msi_free(query);
1484 msiobj_release(&row->hdr);
1485 msiobj_release(&dbview->hdr);
1486 return r;
1489 static UINT msi_get_table_labels(MSIDATABASE *db, LPCWSTR table, LPWSTR **labels, DWORD *numlabels)
1491 UINT r, i, count;
1492 MSIRECORD *prec = NULL;
1494 r = MSI_DatabaseGetPrimaryKeys(db, table, &prec);
1495 if (r != ERROR_SUCCESS)
1496 return r;
1498 count = MSI_RecordGetFieldCount(prec);
1499 *numlabels = count + 1;
1500 *labels = msi_alloc((*numlabels)*sizeof(LPWSTR));
1501 if (!*labels)
1503 r = ERROR_OUTOFMEMORY;
1504 goto end;
1507 (*labels)[0] = strdupW(table);
1508 for (i=1; i<=count; i++ )
1510 (*labels)[i] = strdupW(MSI_RecordGetString(prec, i));
1513 end:
1514 msiobj_release( &prec->hdr );
1515 return r;
1518 static UINT msi_get_query_columns(MSIQUERY *query, LPWSTR **columns, DWORD *numcolumns)
1520 UINT r, i, count;
1521 MSIRECORD *prec = NULL;
1523 r = MSI_ViewGetColumnInfo(query, MSICOLINFO_NAMES, &prec);
1524 if (r != ERROR_SUCCESS)
1525 return r;
1527 count = MSI_RecordGetFieldCount(prec);
1528 *columns = msi_alloc(count*sizeof(LPWSTR));
1529 if (!*columns)
1531 r = ERROR_OUTOFMEMORY;
1532 goto end;
1535 for (i=1; i<=count; i++ )
1537 (*columns)[i-1] = strdupW(MSI_RecordGetString(prec, i));
1540 *numcolumns = count;
1542 end:
1543 msiobj_release( &prec->hdr );
1544 return r;
1547 static UINT msi_get_query_types(MSIQUERY *query, LPWSTR **types, DWORD *numtypes)
1549 UINT r, i, count;
1550 MSIRECORD *prec = NULL;
1552 r = MSI_ViewGetColumnInfo(query, MSICOLINFO_TYPES, &prec);
1553 if (r != ERROR_SUCCESS)
1554 return r;
1556 count = MSI_RecordGetFieldCount(prec);
1557 *types = msi_alloc(count*sizeof(LPWSTR));
1558 if (!*types)
1560 r = ERROR_OUTOFMEMORY;
1561 goto end;
1564 *numtypes = count;
1565 for (i=1; i<=count; i++ )
1567 (*types)[i-1] = strdupW(MSI_RecordGetString(prec, i));
1570 end:
1571 msiobj_release( &prec->hdr );
1572 return r;
1575 static void merge_free_rows(MERGETABLE *table)
1577 struct list *item, *cursor;
1579 LIST_FOR_EACH_SAFE(item, cursor, &table->rows)
1581 MERGEROW *row = LIST_ENTRY(item, MERGEROW, entry);
1583 list_remove(&row->entry);
1584 msiobj_release(&row->data->hdr);
1585 msi_free(row);
1589 static void free_merge_table(MERGETABLE *table)
1591 UINT i;
1593 if (table->labels != NULL)
1595 for (i = 0; i < table->numlabels; i++)
1596 msi_free(table->labels[i]);
1598 msi_free(table->labels);
1601 if (table->columns != NULL)
1603 for (i = 0; i < table->numcolumns; i++)
1604 msi_free(table->columns[i]);
1606 msi_free(table->columns);
1609 if (table->types != NULL)
1611 for (i = 0; i < table->numtypes; i++)
1612 msi_free(table->types[i]);
1614 msi_free(table->types);
1617 msi_free(table->name);
1618 merge_free_rows(table);
1620 msi_free(table);
1623 static UINT msi_get_merge_table (MSIDATABASE *db, LPCWSTR name, MERGETABLE **ptable)
1625 UINT r;
1626 MERGETABLE *table;
1627 MSIQUERY *mergeview = NULL;
1629 static const WCHAR query[] = {'S','E','L','E','C','T',' ','*',' ',
1630 'F','R','O','M',' ','`','%','s','`',0};
1632 table = msi_alloc_zero(sizeof(MERGETABLE));
1633 if (!table)
1635 *ptable = NULL;
1636 return ERROR_OUTOFMEMORY;
1639 r = msi_get_table_labels(db, name, &table->labels, &table->numlabels);
1640 if (r != ERROR_SUCCESS)
1641 goto err;
1643 r = MSI_OpenQuery(db, &mergeview, query, name);
1644 if (r != ERROR_SUCCESS)
1645 goto err;
1647 r = msi_get_query_columns(mergeview, &table->columns, &table->numcolumns);
1648 if (r != ERROR_SUCCESS)
1649 goto err;
1651 r = msi_get_query_types(mergeview, &table->types, &table->numtypes);
1652 if (r != ERROR_SUCCESS)
1653 goto err;
1655 list_init(&table->rows);
1657 table->name = strdupW(name);
1658 table->numconflicts = 0;
1660 msiobj_release(&mergeview->hdr);
1661 *ptable = table;
1662 return ERROR_SUCCESS;
1664 err:
1665 msiobj_release(&mergeview->hdr);
1666 free_merge_table(table);
1667 *ptable = NULL;
1668 return r;
1671 static UINT merge_diff_tables(MSIRECORD *rec, LPVOID param)
1673 MERGEDATA *data = param;
1674 MERGETABLE *table;
1675 MSIQUERY *dbview = NULL;
1676 MSIQUERY *mergeview = NULL;
1677 LPCWSTR name;
1678 UINT r;
1680 static const WCHAR query[] = {'S','E','L','E','C','T',' ','*',' ',
1681 'F','R','O','M',' ','`','%','s','`',0};
1683 name = MSI_RecordGetString(rec, 1);
1685 r = MSI_OpenQuery(data->merge, &mergeview, query, name);
1686 if (r != ERROR_SUCCESS)
1687 goto done;
1689 if (TABLE_Exists(data->db, name))
1691 r = MSI_OpenQuery(data->db, &dbview, query, name);
1692 if (r != ERROR_SUCCESS)
1693 goto done;
1695 r = merge_verify_colnames(dbview, mergeview);
1696 if (r != ERROR_SUCCESS)
1697 goto done;
1699 r = merge_verify_primary_keys(data->db, data->merge, name);
1700 if (r != ERROR_SUCCESS)
1701 goto done;
1704 r = msi_get_merge_table(data->merge, name, &table);
1705 if (r != ERROR_SUCCESS)
1706 goto done;
1708 data->curtable = table;
1709 data->curview = mergeview;
1710 r = MSI_IterateRecords(mergeview, NULL, merge_diff_row, data);
1711 if (r != ERROR_SUCCESS)
1713 free_merge_table(table);
1714 goto done;
1717 list_add_tail(data->tabledata, &table->entry);
1719 done:
1720 msiobj_release(&dbview->hdr);
1721 msiobj_release(&mergeview->hdr);
1722 return r;
1725 static UINT gather_merge_data(MSIDATABASE *db, MSIDATABASE *merge,
1726 struct list *tabledata)
1728 static const WCHAR query[] = {
1729 'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
1730 '`','_','T','a','b','l','e','s','`',0};
1731 MSIQUERY *view;
1732 MERGEDATA data;
1733 UINT r;
1735 r = MSI_DatabaseOpenViewW(merge, query, &view);
1736 if (r != ERROR_SUCCESS)
1737 return r;
1739 data.db = db;
1740 data.merge = merge;
1741 data.tabledata = tabledata;
1742 r = MSI_IterateRecords(view, NULL, merge_diff_tables, &data);
1743 msiobj_release(&view->hdr);
1744 return r;
1747 static UINT merge_table(MSIDATABASE *db, MERGETABLE *table)
1749 UINT r;
1750 MERGEROW *row;
1751 MSIVIEW *tv;
1753 if (!TABLE_Exists(db, table->name))
1755 r = msi_add_table_to_db(db, table->columns, table->types,
1756 table->labels, table->numlabels, table->numcolumns);
1757 if (r != ERROR_SUCCESS)
1758 return ERROR_FUNCTION_FAILED;
1761 LIST_FOR_EACH_ENTRY(row, &table->rows, MERGEROW, entry)
1763 r = TABLE_CreateView(db, table->name, &tv);
1764 if (r != ERROR_SUCCESS)
1765 return r;
1767 r = tv->ops->insert_row(tv, row->data, -1, FALSE);
1768 tv->ops->delete(tv);
1770 if (r != ERROR_SUCCESS)
1771 return r;
1774 return ERROR_SUCCESS;
1777 static UINT update_merge_errors(MSIDATABASE *db, LPCWSTR error,
1778 LPWSTR table, DWORD numconflicts)
1780 UINT r;
1781 MSIQUERY *view;
1783 static const WCHAR create[] = {
1784 'C','R','E','A','T','E',' ','T','A','B','L','E',' ',
1785 '`','%','s','`',' ','(','`','T','a','b','l','e','`',' ',
1786 'C','H','A','R','(','2','5','5',')',' ','N','O','T',' ',
1787 'N','U','L','L',',',' ','`','N','u','m','R','o','w','M','e','r','g','e',
1788 'C','o','n','f','l','i','c','t','s','`',' ','S','H','O','R','T',' ',
1789 'N','O','T',' ','N','U','L','L',' ','P','R','I','M','A','R','Y',' ',
1790 'K','E','Y',' ','`','T','a','b','l','e','`',')',0};
1791 static const WCHAR insert[] = {
1792 'I','N','S','E','R','T',' ','I','N','T','O',' ',
1793 '`','%','s','`',' ','(','`','T','a','b','l','e','`',',',' ',
1794 '`','N','u','m','R','o','w','M','e','r','g','e',
1795 'C','o','n','f','l','i','c','t','s','`',')',' ','V','A','L','U','E','S',
1796 ' ','(','\'','%','s','\'',',',' ','%','d',')',0};
1798 if (!TABLE_Exists(db, error))
1800 r = MSI_OpenQuery(db, &view, create, error);
1801 if (r != ERROR_SUCCESS)
1802 return r;
1804 r = MSI_ViewExecute(view, NULL);
1805 msiobj_release(&view->hdr);
1806 if (r != ERROR_SUCCESS)
1807 return r;
1810 r = MSI_OpenQuery(db, &view, insert, error, table, numconflicts);
1811 if (r != ERROR_SUCCESS)
1812 return r;
1814 r = MSI_ViewExecute(view, NULL);
1815 msiobj_release(&view->hdr);
1816 return r;
1819 UINT WINAPI MsiDatabaseMergeW(MSIHANDLE hDatabase, MSIHANDLE hDatabaseMerge,
1820 LPCWSTR szTableName)
1822 struct list tabledata = LIST_INIT(tabledata);
1823 struct list *item, *cursor;
1824 MSIDATABASE *db, *merge;
1825 MERGETABLE *table;
1826 BOOL conflicts;
1827 UINT r;
1829 TRACE("(%d, %d, %s)\n", hDatabase, hDatabaseMerge,
1830 debugstr_w(szTableName));
1832 if (szTableName && !*szTableName)
1833 return ERROR_INVALID_TABLE;
1835 db = msihandle2msiinfo(hDatabase, MSIHANDLETYPE_DATABASE);
1836 merge = msihandle2msiinfo(hDatabaseMerge, MSIHANDLETYPE_DATABASE);
1837 if (!db || !merge)
1839 r = ERROR_INVALID_HANDLE;
1840 goto done;
1843 r = gather_merge_data(db, merge, &tabledata);
1844 if (r != ERROR_SUCCESS)
1845 goto done;
1847 conflicts = FALSE;
1848 LIST_FOR_EACH_ENTRY(table, &tabledata, MERGETABLE, entry)
1850 if (table->numconflicts)
1852 conflicts = TRUE;
1854 r = update_merge_errors(db, szTableName, table->name,
1855 table->numconflicts);
1856 if (r != ERROR_SUCCESS)
1857 break;
1859 else
1861 r = merge_table(db, table);
1862 if (r != ERROR_SUCCESS)
1863 break;
1867 LIST_FOR_EACH_SAFE(item, cursor, &tabledata)
1869 MERGETABLE *table = LIST_ENTRY(item, MERGETABLE, entry);
1870 list_remove(&table->entry);
1871 free_merge_table(table);
1874 if (conflicts)
1875 r = ERROR_FUNCTION_FAILED;
1877 done:
1878 msiobj_release(&db->hdr);
1879 msiobj_release(&merge->hdr);
1880 return r;
1883 MSIDBSTATE WINAPI MsiGetDatabaseState( MSIHANDLE handle )
1885 MSIDBSTATE ret = MSIDBSTATE_READ;
1886 MSIDATABASE *db;
1888 TRACE("%d\n", handle);
1890 db = msihandle2msiinfo( handle, MSIHANDLETYPE_DATABASE );
1891 if( !db )
1893 MSIHANDLE remote_database = msi_get_remote(handle);
1894 if ( !remote_database )
1895 return MSIDBSTATE_ERROR;
1897 WARN("MsiGetDatabaseState not allowed during a custom action!\n");
1899 return MSIDBSTATE_READ;
1902 if (db->mode != MSIDBOPEN_READONLY )
1903 ret = MSIDBSTATE_WRITE;
1904 msiobj_release( &db->hdr );
1906 return ret;
1909 MSICONDITION __cdecl remote_DatabaseIsTablePersistent(MSIHANDLE db, LPCWSTR table)
1911 return MsiDatabaseIsTablePersistentW(db, table);
1914 HRESULT __cdecl remote_DatabaseGetPrimaryKeys(MSIHANDLE db, LPCWSTR table, MSIHANDLE *keys)
1916 UINT r = MsiDatabaseGetPrimaryKeysW(db, table, keys);
1917 return HRESULT_FROM_WIN32(r);
1920 HRESULT __cdecl remote_DatabaseGetSummaryInformation(MSIHANDLE db, UINT updatecount, MSIHANDLE *suminfo)
1922 UINT r = MsiGetSummaryInformationW(db, NULL, updatecount, suminfo);
1923 return HRESULT_FROM_WIN32(r);
1926 UINT __cdecl remote_DatabaseOpenView(MSIHANDLE db, LPCWSTR query, MSIHANDLE *view)
1928 return MsiDatabaseOpenViewW(db, query, view);